Suppose I create an array of vectors, and then I allocate memory for num_vectors
many vectors.
What happens when delete
gets executed after making some push_back
operations in random vector elements? I wonder if all the allocated memory (by new
and push_back
) gets freed.
int num_vectors = 123456;
std::vector<uint64_t>* arr_vecs;
arr_vecs = new std::vector<uint64_t>[num_vectors];
int random_ix;
int random_val = 999;
random_ix = 1;
arr_vecs[random_ix].push_back(random_val);
random_ix = 88;
arr_vecs[random_ix].push_back(random_val);
random_ix = 123;
arr_vecs[random_ix].push_back(random_val);
delete[] arr_vecs;
The question is not about good/bad practices in modern C++. I rather ask a specific question.
It seems like it gets freed, however I would like to have a better intuition about the expected behavior.
Yes it does, the delete operator will call the array's object destructors and in the std::vector destructor the memory that the vector has allocated is freed.
arr_vecs = new std::vector<uint64_t>[num_vectors];
//will create "num_vectors" of vectors calling default constructor for each
delete[] arr_vecs;
//calls delete on each newed object which calls the destructor of the object
it is advised to use a vector of vectors if you need multidimensional arrays, or you could create a 1D array and map your N-D array to 1D by simple math.