If I declare a temporary auto deleted character buffer using
std::auto_ptr<char> buffer(new char[n]);
then the buffer is automatically deleted when the buffer goes out of scope. I would assume that the buffer is deleted using delete.
However the buffer was created using new[], and so strictly speaking the buffer should be deleted using delete[].
What possibility is there that this mismatch might cause a memory leak?
Functionally, C++11's std::unique_ptr is the "fixed" std::auto_ptr: both of them are suitable when - at any point in time during execution - there should be a single smart-pointer owner for a pointed-to object. The crucial difference is in copy-construction or assignment from another un-expiring smart pointer, shown on the => lines below:
The direct replacement for auto_ptr (or the closest thing to one anyway) is unique_ptr. As far as the "problem" goes, it's pretty simple: auto_ptr transfers ownership when it's assigned. unique_ptr also transfers ownership, but thanks to codification of move semantics and the magic of rvalue references, it can do so considerably more naturally.
std::auto_ptr auto_ptr is a smart pointer that manages an object obtained via new expression and deletes that object when auto_ptr itself is destroyed.
Because of these unusual copy semantics, auto_ptr may not be placed in standard containers. std::unique_ptr is preferred for this and other uses. (since C++11) 2) Specialization for type void is provided, it declares the typedef element_type, but no member functions.
The behaviour of calling delete on a pointer allocated with new[] is undefined. As you assumed, auto_ptr does call delete when the smart pointer goes out of scope. It's not just memory leaks you have to worry about -- crashes and other odd behaviours are possible.
If you don't need to transfer the ownership of the pointer, Boost's scoped_array class might be what you're looking for.
I would use a vector of char as the buffer.
std::vector<char> buffer(size);
read(input,&buffer[0],size);
Basically you don't even want to call new if you don't need to.
A vector provides a run-time sized buffer that you can use just like an array (buffer).
The best part is that the vector cleans up after itself and the standard guarantees that all element in the vector will be in contigious storage. Perfect for a buffer.
Or more formaly the guarantee is:
(&buffer[0]) + size == (&buffer[size])
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