An abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking
Smart pointers are objects that look and feel like pointers, but are smarter.
What does this mean? To look and feel like pointers, smart pointers need to have the same interface that pointers do: they need to support pointer operations like dereferencing (operator *
) and indirection (operator ->
). An object that looks and feels like something else is called a proxy object, or just proxy. The proxy pattern and its many uses are described in the books Design Patterns and Pattern Oriented Software Architecture.
To be smarter than regular pointers, smart pointers need to do things that regular pointers don't. What could these things be? Probably the most common bugs in C++ (and C) are related to pointers and memory management: dangling pointers, memory leaks, allocation failures and other joys. Having a smart pointer take care of these things can save a lot of aspirin...
The simplest example of a smart pointer is auto_ptr
, which is included in the standard C++ library (C++03). You can find it in the header <memory>
, or take a look at Scott Meyers' auto_ptr
implementation. Here is the relevant parts of auto_ptr
's implementation, to illustrate what it does:
template <class T> class auto_ptr
{
T* ptr;
public:
explicit auto_ptr(T* p = 0) : ptr(p) {}
~auto_ptr() {delete ptr;}
T& operator*() {return *ptr;}
T* operator->() {return ptr;}
// ...
};
As shown, auto_ptr
is a simple wrapper around a regular pointer. It forwards all meaningful operations to this pointer (dereferencing and indirection). Its "smartness" is in the destructor: the destructor takes care of deleting the pointer.
For the user of auto_ptr
, this means that instead of writing:
void foo()
{
MyClass* p(new MyClass);
p->DoSomething();
delete p;
}
You can write:
void foo()
{
auto_ptr<MyClass> p(new MyClass);
p->DoSomething();
}
And trust p
to clean-up after itself.
Smart pointers form part of the idiomatic RAII (Resource Acquisition Is Initialisation) technique that is core to resource management in C++.
Links: