std::auto_ptr best practices

One of the frustrating aspects of programming in C++ is memory management.

In Java this is, in large part, handled by the garbage collector. As long as you don’t keep references lying about that you don’t need, and the GC gets called occasionally, Java does a good job cleaning itself up. This makes memory management a little less of a hassle in Java.

When programming in C++, you don’t have as easy a time of it. The programmer is responsible for the allocation and deallocation of objects. There’s no standard garbage collector running in the background to bail you out. If you don’t delete your objects, they’ll hand around for the life of your program.

One nice standard object wrapper is the std::auto_ptr. This takes a standard object pointer and wraps it in friendlier semantics. I was trying to explain std::auto_ptr to a coworker when I found this excellent [best practices](http://www.gotw.ca/publications/using_auto_ptr_effectively.htm)%5B guide](http://www.gotw.ca/publications/using_auto_ptr_effectively.htm) to their use.

Std::auto_ptr does have limitations. You don’t want to put them in collections because they won’t behave the way you’d expect them to behave.

From C++ TPL by Stroustrup 14.4.2:

… auto_ptrs have a copy semantics that differs radically from that of ordinary pointers: When one auto_ptr is copied into another, the source no longer points to anything.

Note that auto_ptr’s destructive copy semantics means it does not meet the requirements for elements of a standard container or for standard algorithms such as sort().

The auto_ptr copy constructor changes the owership of the underlying object. If you place an auto_ptr in a container, more than likely your original reference will be deleted. When you ‘get’ an object from such a container, more than likely the object in the container will be deleted. This is all implementation-specific.

Let’s just say what the standard says – using auto_ptrs in containers results in undefined behavior. The last thing you want is undefined behavior.

Auto_ptrs are also not generic referenced-counted objects. You can add this behavior pretty easily. Out of the box, however, you don’t want to assign the same object to two different std::auto_ptrs. This results in a double delete of the underlying pointer, which is typically consider a very bad thing. Don’t do it.

Even with these limitiations, the std::auto_ptr is a very nice tool to have when programming in C++. They’re invaluable when you’re trying to figure out who owns which object and who is responsible for deleting it. Use them wisely and they can save you a lot of headaches.

Tagged with: , ,
Posted in Uncategorized
Design a site like this with WordPress.com
Get started