I found myself in a situation where I would have liked to have an analog of unique_ptr's release() for std::vector<>. 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
functionUsingAndInternallyDeletingRowPointer(data);
Is there a particular reason why this kind of possibility is not provided? May that impose some constraint on std::vector's the internal implementation?
Or there is a way to achieve this that I am embarrassingly missing?
functionUsingAndInternallyDeletingRowPointer
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>>::destroy.
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.
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