Monday, July 21, 2008

C++ auto_ptr

Class auto_ptr and Dynamic Memory Allocation
A common programming practice is to allocate dynamic memory, assign the address of that memory to a pointer, use the pointer to manipulate the memory and deallocate the memory with delete when the memory is no longer needed. If an exception occurs after successful memory allocation but before the delete statement executes, a memory leak could occur. The C++ standard provides class template auto_ptr in header file to deal with this situation.

An object of class auto_ptr maintains a pointer to dynamically allocated memory. When an auto_ptr object destructor is called (for example, when an auto_ptr object goes out of scope), it performs a delete operation on its pointer data member. Class template auto_ptr provides overloaded operators * and -> so that an auto_ptr object can be used just as a regular pointer variable is.

http://www.deitel.com/articles/cplusplus_tutorials/20060304/

http://www.gotw.ca/publications/using_auto_ptr_effectively.htm