C++ Programming/Operators/Pointers/Smart Pointers

Smart Pointers
Using raw pointers to store allocated data and then cleaning them up in the destructor can generally be considered a very bad idea since it is error-prone. Even temporarily storing allocated data in a raw pointer and then deleting it when done with it should be avoided for this reason. For example, if your code throws an exception, it can be cumbersome to properly catch the exception and delete all allocated objects.

Smart pointers can alleviate this headache by using the compiler and language semantics to ensure the pointer content is automatically released when the pointer itself goes out of scope.

Semantics
The auto_ptr has semantics of strict ownership, meaning that the auto_ptr instance is the sole entity responsible for the object's lifetime. If an auto_ptr is copied, the source loses the reference. For example:

This code will print a NULL address for the first auto_ptr object and some non-NULL address for the second, showing that the source object lost the reference during the assignment (=). The raw pointer  in the example should not be deleted, as it will be deleted by the auto_ptr that owns the reference. In fact,  could be passed directly into x, eliminating the need for.

Notice that the object pointed by an auto_ptr is destructed using ; this means that you should only use auto_ptr for pointers obtained with. This excludes pointers returned by  and.