简体   繁体   中英

Canonical Way to Delete a Vector Allocated on The Heap in C++17

I have searched stack overflow, but it seems the previous answers are potentially outdated, or just not very clear.

My question is the following:

I want to store a huge amount of data in a vector. To do this, I will allocate the vector on the heap as follows:

#include <vector>
std::vector<int> *vector = new std::vector<int> (1000000000);

Now suppose I use this vector in a large matrix computation. I want to now free it.

What is the canonical way to do this in c++17?

I know that for an array the riff would be as follows:

int *arr = new int[1000000000];
delete[] arr

What is the equivalent (and most efficient) way to do this for an stl vector?

The thing with std::vector is that its data is always on the heap.

Hence you don't have to allocate the std::vector itself on the heap.

std::vector makes use of a principle called RAII (Resource Acquisition is Initialization), it means that when it's done with memory, it de-allocates it for you.

Hence, doing this is sufficient

{
std::vector<int> x{};
for (size_t i = 0; i < 50000; i++) x.push_back(x);
} // x gets out of scope, memory is freed

You don't have to manually free the std::vector 's memory.

Now, say you'd allocate the std::vector itself on the heap, for whatever reason. Then you'd have to use delete vector; to free it. In this scenario, I would suggest std::unique_ptr<std::vector<T>> though, as it also makes use of the same principle (RAII).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM