Emerald Weapon Emerald Weapon - 1 year ago 99
C++ Question

Why std::vector does not have a release method?

I found myself in a situation where I would have liked to have an analog of

. E.g.:

std::vector<int> v(SOME_SIZE);

//.. performing operations on v

int* data = v.release(); // v.size() is now 0 and the ownership of the internal array is released

Is there a particular reason why this kind of possibility is not provided? May that impose some constraint on
's the internal implementation?

Or there is a way to achieve this that I am embarrassingly missing?

Answer Source


And what exactly would this function do? Because that memory was allocated by calling std::allocator_traits<std::allocator<T>>::allocate, which expects it to be deleted by calling std::allocator_traits<std::allocator<T>>::deallocate. Furthermore, each element of the vector was constructed with a call to std::allocator_traits<std::allocator<T>>::construct, and therefore must be destroyed by a call to std::allocator_traits<std::allocator<T>>::destruct.

If that function tries to do delete [] on that pointer, it won't work. Or at the very least, it isn't required to work.

It might be reasonable to be able to extract a memory buffer from a vector and use it directly. But it could not be a mere pointer. It would have to have an allocator along with it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download