All examples will assume, you are using the newly approved but not yet officially published C++0x standard, if you can't or won't use this, all classes/constructs here are implemented in the excellent boost library as well. All examples compile with gcc 4.5.2 and the compile flags "g++ -std=c++0x", please post a comment if they do now work on your platform so I can make a note of it. Not all functions of the C++0x are implemented on all platforms.

The memory leak

Let us start by explaining the problem. Whenever you allocate memory on the heap, regardless of the fact you do it with new, new[], or the c memory allocation functions like malloc, you are responsible for cleaning it up by calling the appropriate delete, delete[] or free. If you do not or you do it wrong, you create what is known as a memory leak. This means that memory was allocated that is no longer accessible because you have no pointer any more that refers to it, but it also not freed, so it didn't return to the available pool of memory. If your program runs for a long time and frequently leaks memory it will in fact use up all available memory in your system, which is bad.

Difficulties in memory management

Wise people once said that you should match every call that allocates memory with the appropriate call that deallocated the memory. new/delete, new[]/delete[], malloc/free. But even then you have to make certain that the statement which deallocates the memory is actually reached.
A common mistake for example which can even catch experienced programmers off guard is when the program throws an error, you catch the error and recover, but by skipping all the code after you throw the error, you miss the statement that would have cleaned up the memory.
Another problem could be that it is not exactly clear where the memory should be freed. It is quite common that a pointer is passed around or copied to more than once place,

Concept of ownership

Smart programmers identified that all variables and memory should have an owner. Someone or something that is responsible for controling the lifetime for a variable or a piece of memory. For local variables and parameters this is the scope they belong to, because if the scope ends so do the parameters and variable. For class members it is the object of the class. If the object dies so do the member variables. For global variables and static variables, this is the program. If the program dies so do the global and static variables.
For memory it is a little bit more difficult, because pointers to memory can be passed around. But if a programmer keeps in mind which classe(s) or scope owns a piece of memory at any given time. Then it becomes automatically clear where and when the memory should be released.

Ownership models

For the purpose of smart pointers we will make the distinction between 3 ownership models.

The memory is owned by the scope: This is just like regular variables, when the scope ends, the memory should be released. If this is the case you probably should have declared a local variable instead of allocating it with new, so it is actually not used as much.

The memory is passed around but only one class or scope can claim ownership at any given time: So the moment the pointer is passed to somewhere else, you will never use it again.

The memory is shared: This is the most flexible ownership model and in fact the default for any language with garbage collection like java. This is saying there is no clear owner, but the memory can be accessed at different places.

To enforce this ownership so the memory will actually be released automatically is the reason smart pointers were invented.

Smart pointers

But first, what is a smart pointer: A smart pointer is an object that contains a pointer and behaves like a pointer, but will automatically release it's memory when certain conditions are met. You create one by passing it a pointer and after that you let the smart pointer take care of delete/delete[]/free, in fact it is an error to try to free the memory manually. For every other purpose but delete/delete[]/free, the pointer behaves just like a regular pointer. It is dereferences with *, you can use the operator -> to call a functions. In addition you can get the underlying pointer with the get() function, but do not call delete on it.

There are different kinds of smart pointers, to enforce the different ownership models, they all reside in the memory header (#include <memory>). Here I will give a quick explanation. Bellow I will go in more depth about each one.

const std::unique_ptr: When a pointer is managed by a const std::unique_ptr, the memory refered to will be freed when the scope in which a const std::unique_ptr exists ends. (This is almost equivalent to the behavior of a boost::scoped_ptr)

std::unique_ptr: When a pointer is managed by a unique pointer, the memory will be freed when the owning class or scope dies/ends unless the pointer/memory is MOVED to another std::unique_ptr. It is also no longer allowed to use the unique_ptr after it/it's memory has been moved.

std::shared_ptr: When a pointer is managed by a shared pointer, the memory/pointer can be COPIED to other std::shared_ptr. When no more copies of a particular std::shared_ptr exists, the memory will be freed. This is almost (read pitfalls to understand the almost) has the same effect as automatic garbage collection like in languages such as java and most scripting languages.

This should be pretty self explanatory. Notice that the unique_pointer does need a type as template parameter. Also notice that I call new when creating the smart pointer, you do not have to do this, but it is actually recommended. By never explicitly creating the actual pointer, I certainly will not be tempted to use it. Mixing regular pointers and smart pointers referring to the same is a recipe for disaster.

std::unique_ptr

This time the example is a bit trickier. Even to experienced c++ programmers, this can look a little bit alien as unique_ptr has close ties with a new language feature rvalue references and move semantics. There is an excellent introduction here http://www.open-std....2006/n2027.html, but for the purpose of this smart pointer tutorial I will give a brief explanation of what we actually use here.

#include <memory>
class A {
public:
//move the integer in but do not automatically claim ownership, ownership must be released by the caller
void move_int_in(std::unique_ptr<int>&& an_int_) {
an_int = std::move(an_int_);
}
//move the integer out, but doesn't automatically release ownership
std::unique_ptr<int>& move_int_out() {
return an_int;
}
std::unique_ptr<int> an_int;
};
int main() {
std::unique_ptr<int> the_int(new int(5));
std::unique_ptr<int> the_same_int = std::move(the_int);
//don't use the_int after this point, it does no longer has ownership
A a;
//With these two function the caller must explicitly release
//and take ownership with std::move
a.move_int_in(std::move(the_int)); //the_same_int releases ownership
the_same_int = std::move(a.move_int_out()); //the_same_int takes ownership
} //the_same_int currently had ownership and died because it went out of scope, the memory is released

This is how ownership of a pointer is moved. Notice that the std::move is necessary, it means, release ownership from the smart pointer on the right and give it to the smart pointer to the right. After this call, you should no longer use the_int to refer to the integer, doing so will probably result in a segmentation fault.

The class example uses a new feature of c++0x, move semantics. We know about passing values by value, by pointer, by reference, but now there is a 4th way in c++, by move semantics. Basically this means that you can now move values to a function without copying them or creating a reference to an existing object, causing no overhead. But a condition is that the value to the right will never be used again. This behavior is invoked when a parameter or a value to the right of an assignment is a temporary object or when you explicitly state that it is safe to move the object by using std::move. Passing values by move semantics is indicated by the new operator &&.

Now the function move_int_in should make sense. move_int_in takes a parameter of type std::unique_ptr<int>&&, so a std::unique_ptr<int>, but only if it safe to move.

If you don't want the std::move in your calling code, then this can be achieved as well, but it is not recommended. Remember the age old mantra explicit is better than implicit.

#include <memory>
class A {
public:
//move the integer in from a smart pointer and automatically claim ownership
void move_int_in_and_take_ownership(std::unique_ptr<int>& an_int_) {
an_int = std::move(an_int_);
}
//move the integer out and automatically release ownership even when no-one is there to take ownership
std::unique_ptr<int> move_int_out_and_release_ownership() {
return std::move(an_int);
}
std::unique_ptr<int> an_int;
};
int main() {
std::unique_ptr<int> the_int(new int(5));
std::unique_ptr<int> the_same_int = std::move(the_int);
//don't use the_int after this point, it does no longer has ownership
A a;
//With these two functions the class automatically takes
//ownership of the memory/pointer, see also the function
//definitions within the class
a.move_int_in_and_take_ownership(the_same_int); //the_same_int releases ownership, see class
the_same_int = a.move_int_out_and_release_ownership(); //the_same_int takes ownership, see class
}

Note that the stl containers in c++0x now also work with move semantics. It is perfectly valid and safe to create an stl container that contains unique_ptr or in fact any other type of smart pointer and if an element of the stl container is erased, the memory will be freed through the dynamics of the chosen smart pointer. So you can do something like this.

The code should be pretty self explanatory, you can have a piece of memory shared all over the place and yet proper cleanup will happen. The programmer needs not to be aware who still has access to the memory. When the last shared pointer pointing to the memory dies, so does the memory.

Now under some circumstances you want a copy of a shared pointer that does not prevent its destruction. For example you want to be able to do something with an object, but only if it still exists, also read pitfalls for other situations this could be useful. For this purpose there exists the std::weak_ptr.

A weak_ptr in itself doesn't do very much, it doesn't for example let you manipulate it like a pointer. You can however call expired() on it, to let you know if the object it points to still exists and you can create a shared_ptr out of it, that you can manipulate if it does.

Note that it is now unsafe to use the_int as it now no longer owns the pointer to the int. std::move also causes slightly less overhead.

Shared pointers can also safely be stored within stl containers. In fact they will actually use the std::move internally when appropriate, so they cause less overhead.

So it works with new, but does it also work with new[] and malloc ?

Yes, but not automatically. A smart pointer actually takes 2 parameters, a pointer and a deleter. It is upto the user to properly match the deleter, where plain delete is the default. If you allocate memory with new[] or malloc, you should create your smart pointers as follows:

std::unique_ptr<int[]> a(new int[5]);

This gives access to the operator [] on a, so you can work with it like an array, and will properly call delete[]

For memory allocated with the malloc family of allocation functions, you can use:

You can do even fancier things with the custom deleter, for example a deleter that also closes a file descriptor comes to mind.

Ofcourse the same will work with shared_ptr.

Note on performance

The performance overhead of smart pointers is really quite small. In fact for a unique_ptr no extra memory is used and moving one is the same amount of work as copying one address and assigning zero to the original pointer, which is recommended you do with regular pointers anyway. So unique_ptr, properly implemented has no overhead. shared_ptr has a little overhead, it maintains a count of all smart pointers sharing a pointer. So every time a shared_ptr is created or destroyed a reference count is incremented or decremented and when it is decremented it is checked.

Pitfalls

Unfortunately smart pointers can not always be relied upon to free memory. Consider the following example.

The solution would be to make one of the two shared_ptr a str::weak_ptr

This and only this is the advantage automatic garbage collection has over smart pointers. It will detect these kinds of cycles but usually at much greater computational cost to the garbage collector.

FAQ

Is there anyway to release my pointers from the grasp of smart pointers ?

You can release your pointer from a unique_ptr, this is safe and is not in breach of the contract of the unique_ptr. Just call release() on a unique_ptr. This is the same as moving a pointer out of a smart pointer. You cannot do this with a shared_ptr. So once you wrap a pointer into a shared pointer, you have no way to unwrap it again.

Can I copy a unique_ptr ?

No you can not. It goes against the contract of a unique_ptr, making a copy wouldn't make it unique.

can I really not make a copy ?

Well, not really, as always you can work your way around it, but it isn't pretty, and using anything but the last created copy is unsafe. Basically what you end up with is the behavior of auto_ptr, which was deprecated for a reason.

#ifndef COPYABLE_UNIQUE_PTR_H
#define COPYABLE_UNIQUE_PTR_H
#include <memory>
/** Usage of this class is only safe if you can guarantee that only the most recent copy
* of the smart pointer will be used. It uses move on copy semantics like the deprecated
* auto_ptr.
*/
template <class T, class Del = std::default_delete<T> >
class copyable_unique_ptr : public std::unique_ptr<T, Del> {
public:
//A fully C++0x compliant c++ compiler should accept the following line to inherit constructors from unique_ptr.
//gcc as of 4.5.2 with -std=c++0x, however does not. So we manually write wrappers for the constructors we need
//using std::unique_ptr<T, Del>::std::unique_ptr<T, Del>;
copyable_unique_ptr(T* pointer, Del deleter = Del()) : std::unique_ptr<T, Del>(pointer, deleter) {}
copyable_unique_ptr(std::unique_ptr<T,Del>& pointer) : std::unique_ptr<T, Del>(std::move(pointer)) {}
//copy constructors which moves the pointer from the old unique_ptr to the new one when copied.
copyable_unique_ptr(const copyable_unique_ptr<T,Del>& other) : std::unique_ptr<T, Del>(std::move(const_cast<copyable_unique_ptr<T,Del>& >(other))) {}
};
#endif // COPYABLE_UNIQUE_PTR_H

I've used it to be able to use a unique_ptr with boost::bind, when I knew the boost bind function object would only be called once. But it is not recommended the const_cast is also a sign for the compiler to abandon many optimizations.