The first solution is:
std::vector<int> *vec = new std::vector<int>; assert(vec != NULL); // ... delete vec;
An alternative is:
std::vector<int> v; //... vec.clear(); vec.swap(std::vector<int>(vec));
The second solution's a bit of a trick --- what's the "right" way to do it?
I'm aware that the destructor will be called once it's off the stack, I was curious about other methods.
C++ Vector Library - clear() Function The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.
All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.
The vector (like all standard containers) owns the objects inside it. So it is responsible for destroying them. Note: If you vector contains pointers then it owns the pointers (not what the pointers point at). So these need to be deleted.
The simplest and most reliable way to deallocate a vector is to declare it on the stack and simply do nothing.
void Foo() { std::vector<int> v; ... }
C++ guarantees that the destructor of v
will be called when the method executes. The destructor of std::vector
will ensure any memory it allocated is freed. As long as the T
type of the vector<T>
has proper C++ deallocation semantics all will be well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With