Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to use auto_ptr with new char[n]

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?

like image 362
David Sykes Avatar asked Nov 04 '08 09:11

David Sykes


People also ask

What is the difference between auto_ptr and unique_ptr in C++11?

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:

What is the replacement for auto_ptr?

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.

What is auto_ptr in C++?

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.

Why can't auto_ptr be placed in a standard container?

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.


2 Answers

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.

like image 110
Stephen Veiss Avatar answered Sep 22 '22 22:09

Stephen Veiss


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])
like image 44
Martin York Avatar answered Sep 19 '22 22:09

Martin York