Unsafe use of smart pointers

Ubiquitous use of smart pointers can prevent memory leaks and make for much easier to read and understand code. Unfortunately, as with most things C++, there are some caveats you need to be aware of otherwise your attempts to write robust code could very well come back to bite you. This little quiz shows how careless misuse of auto_ptr could open up a big can of worms.

Question: What’s wrong with this?

std::auto_ptr pInt(new int[10]);

Answer: The result of auto_ptr deleting the memory allocated to it is undefined.

Why?

The auto_ptr calls non-array delete on memory allocated using array new. The C++ standard defines the result of this as undefined (even for intrinsic types, contrary to popular belief). It is important to match the correct allocator with its counter-part. Scalar new should always use scalar delete and array new should always use array delete. Since there is no array version of auto_ptr you cannot not use it to manage the allocation of arrays from the heap.

Of course, the question is why would you even bother? The C++ standard provides you with the vector type, which is basically a managed array. The C++ Standard even goes as far as to explicitly guarantee that its internal memory layout (of its data buffer) is compatible with the C-style array.

NB. As from C++11 the same is true for a string type; however, prior to C++11 there were no guarantees placed on the internal memory layout of the string type.


			

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s