http://ootips.org/yonat/4dev/smart-pointers.html
|
To look and feel like pointers, smart pointers need tohave the same interface that pointers do: they need to support pointeroperations like dereferencing (operator *) and indirection(operator ->). An object that looks and feels like something else iscalled a proxy object, or just proxy.The proxypattern and its many uses are described in the booksDesign Patterns andPatternOriented Software Architecture.
To be smarter than regular pointers, smart pointers need to dothings that regular pointers don't. What could these things be?Probably the most common bugs in C++ (and C) are related to pointersand memory management: dangling pointers, memory leaks, allocationfailures and other joys. Having a smart pointer take care of thesethings can save a lot of aspirin...
The simplest example of a smart pointer is auto_ptr, which isincluded in the standard C++ library. You can find it in the header<memory>, or take a look atScottMeyers' auto_ptr implementation. Here is part of auto_ptr'simplementation, to illustrate what it does:
As you can see, auto_ptr is a simple wrapper around a regular pointer.It forwards all meaningful operations to this pointer (dereferencingand indirection). Its smartness in the destructor: the destructor takescare of deleting the pointer.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;} // ... };
For the user of auto_ptr, this means that instead of writing:
You can write:void foo() { MyClass* p(new MyClass); p->DoSomething(); delete p; }
And trust p to cleanup after itself.void foo() { auto_ptr<MyClass> p(new MyClass); p->DoSomething(); }
What does this buy you? See the next section.
Automatic initialization.Another nice thing is that you don't need to initialize the auto_ptr toNULL, since the default constructor does that for you. This is one lessthing for the programmer to forget.
Dangling pointers.A common pitfall of regular pointers is the dangling pointer: a pointerthat points to an object that is already deleted. The following codeillustrates this situation:
For auto_ptr, this is solved by setting its pointer to NULL when it is copied:MyClass* p(new MyClass); MyClass* q = p; delete p; p->DoSomething(); // Watch out! p is now dangling! p = NULL; // p is no longer dangling q->DoSomething(); // Ouch! q is still dangling!
Other smart pointers may do other things when they are copied. Here aresome possible strategies for handling the statement q = p, where p andq are smart pointers:template <class T> auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<T>& rhs) { if (this != &rhs) { delete ptr; ptr = rhs.ptr; rhs.ptr = NULL; } return *this; }
What happens if DoSomething() throws an exception? All the lines afterit will not get executed and p will never get deleted! If we're lucky,this leads only to memory leaks. However, MyClass may free some otherresources in its destructor (file handles, threads, transactions, COMreferences, mutexes) and so not calling it my cause severe resourcelocks.void foo() { MyClass* p(new MyClass); p->DoSomething(); delete p; }
If we use a smart pointer, however, p will be cleaned up whenever itgets out of scope, whether it was during the normal path of executionor during the stack unwinding caused by throwing an exception.
But isn't it possible to write exception safe code with regularpointers? Sure, but it is so painful that I doubt anyone actually doesthis when there is an alternative. Here is what you would do in thissimple case:
Now imagine what would happen if we had some if's and for'sin there...void foo() { MyClass* p; try { p = new MyClass; p->DoSomething(); delete p; } catch (...) { delete p; throw; } }
A common strategy for using memory more efficiently is copy on write(COW). This means that the same object is shared by many COW pointersas long as it is only read and not modified. When some part of theprogram tries to modify the object ("write"), the COW pointercreates a new copy of the object and modifies this copy instead of theoriginal object. The standard string class is commonly implementedusing COW semantics (see the <string> header).
string s("Hello"); string t = s; // t and s point to the same buffer of characters t += " there!"; // a new buffer is allocated for t before // appending " there!", so s is unchanged.
Optimized allocation schemes are possible when you can make someassumptions about the objects to be allocated or the operatingenvironment. For example, you may know that all the objects will havethe same size, or that they will all live in a single thread. Althoughit is possible to implement optimized allocation schemes usingclass-specific new and delete operators, smart pointers give you thefreedom to choose whether to use the optimized scheme for each object,instead of having the scheme set for all objects of a class. It istherefore possible to match the allocation scheme to differentoperating environments and applications, without modifying the code forthe entire class.
What can you do if you need a collection of objects from differentclasses? The simplest solution is to have a collection of pointers:class Base { /*...*/ }; class Derived : public Base { /*...*/ }; Base b; Derived d; vector<Base> v; v.push_back(b); // OK v.push_back(d); // error
The problem with this solution is that after you're done with thecontainer, you need to manually cleanup the objects stored in it. Thisis both error prone and not exception safe.vector<Base*> v; v.push_back(new Base); // OK v.push_back(new Derived); // OK too // cleanup: for (vector<Base*>::iterator i = v.begin(); i != v.end(); ++i) delete *i;
Smart pointers are a possible solution, as illustrated below. (Analternative solution is a smart container, like the one implemented inpointainer.h.)
Since the smart pointer automatically cleans up after itself, there isno need to manually delete the pointed objects.vector< linked_ptr<Base> > v; v.push_back(new Base); // OK v.push_back(new Derived); // OK too // cleanup is automatic
Note: STL containers may copy and delete their elements behind thescenes (for example, when they resize themselves). Therefore, allcopies of an element must be equivalent, or the wrong copy may be theone to survive all this copying and deleting. This means that somesmart pointers cannot be used within STL containers, specifically thestandard auto_ptr and any ownership-transferring pointer. For more infoabout this issue, seeC++ Guru of theWeek #25.
Using a copied pointer instead of auto_ptr solves this problem: thecopied object (y) gets a new copy of the member.class MyClass { auto_ptr<int> p; // ... }; MyClass x; // do some meaningful things with x MyClass y = x; // x.p now has a NULL pointer
Note that using a reference counted or reference linked pointermeans that if y changes the member, this change will also affect x!Therefore, if you want to save memory, you should use a COW pointer andnot a simple reference counted/linked pointer.
It is important to consider the characteristics of the specificgarbage collection scheme used. Specifically, referencecounting/linking can leak in the case of circular references (i.e.,when the pointed object itself contains a counted pointer, which pointsto an object that contains the original counted pointer). Itsadvantage over other schemes is that it is both simple to implement anddeterministic. The deterministic behavior may be important in some realtime systems, where you cannot allow the system to suddenly wait whilethe garbage collector performs its housekeeping duties.
Generally speaking, there are two ways to implement referencecounting: intrusive and non-intrusive. Intrusive means that the pointedobject itself contains the count. Therefore, you cannot use intrusivereference counting with 3-rd party classes that do not already havethis feature. You can, however, derive a new class from the 3-rd partyclass and add the count to it. Non-intrusive reference countingrequires an allocation of a count for each counted object. Thecounted_ptr.h is an example ofnon-intrusive reference counting.
Reference linking does not require any changes to be made to thepointed objects, nor does it require any additional allocations. Areference linked pointer takes a little more space than a referencecounted pointer - just enough to store one or two more pointers. |
Both reference counting and reference linking require using locks ifthe pointers are used by more than one thread of execution.
Using an owned pointer as the function argument is an explicitstatement that the function is taking ownership of the pointer.
For this: | Use that: |
Local variables | auto_ptr |
Class members | Copied pointer |
STL Containers | Garbage collected pointer (e.g. reference counting/linking) |
Explicit ownership transfer | Owned pointer |
Big objects | Copy on write |
Feel free to use myown smart pointers in your code.
The Boost C++ libraries include somesmart pointers, which are more rigorously tested and actively maintained.Do try them first, if they are appropriate for your needs.