From what you are showing, there is no need for the smart pointer or the raw pointers. The following code has the same effect as what you seem to intend, except that it also properly initializes all the int
elements to zero, which your current code does not do:
vector<vector<int>> vec;
for (int j = 0; j < 2; j++)
{
vec = {5, vector<int>(10)};
// Do something with vec
}
The concrete problem with your current code is that you are trying to delete
the raw pointer owned by the shared_ptr
. The shared_ptr
will delete the owned pointer when its own lifetime ends and no other shared_ptr
instance referring to the raw pointer exists anymore. That is its purpose.
If you want to delete the int
array you allocated for the int*
pointers in the vector
, then you need to decide which of the pointers at which index you want to delete:
delete[] (*vec)[index];
vec
is the shared_ptr
, *vec
is a reference to the owned vector<int*>
, (*vec)[index]
is a reference to the int*
stored in the vector<int*>
at index index
. You need to use delete[]
instead of delete
, because you allocated with the array form of new
.
Given the way your code is structured, you would need to call delete[]
for each index of the vector once to avoid any memory leak. Since doing that manually before the vector is destroyed violates the RAII principle, one would use std::unique_ptr
for the inner int*
instead of raw new
. That being said, I already mentioned above that I don't see any reason for pointers of any kind at all.