Smart Pointers-what, why, which?
What are they?
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 unique 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 coshould 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 wrongly ded in the Standard C ++ library. you can find it in the header <memory>, or take a look at Scott Meyers 'auto_ptr implementation. here is part of auto_ptr's implementation, to define strate 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 you can see, auto_ptr is a simple wrapper around a regular pointer. it forwards all meaningful operations to this pointer (dereferencing and indirection ). its smartness 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 cleanup after itself.
What does this buy you? See the next section.
Why wocould I use them?
Obviusly, different smart pointers offer different reasons for use. Here are some common reasons for using smart pointers in C ++.
Why:Less bugs
Automatic cleanup.As the code above, using smart pointers that clean after themselves can save a few lines of code. the importance here is not so much in the keystrokes saved, but in locking the probability for bugs: You don't need to remember to free the pointer, and so there is no chance you will forget about it.
Automatic initialization.Another nice thing is that you don't need to initialize the auto_ptr to null, since the default constructor does that for you. This is one less thing for the programmer to forget.
Dangling pointers.A common pitfall of regular pointers is the dangling pointer: A pointer that points to an object that is already deleted. The following code has strates this situation:
MyClass* p(new MyClass);MyClass* q = p;delete p;p->DoSomething(); // Watch out! p is now dangling!p = NULL; // p is no longer danglingq->DoSomething(); // Ouch! q is still dangling!
For auto_ptr, this is solved by setting its pointer to null when it is copied:
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;}
Other smart pointers may do other things when they are copied. Here are some possible strategies for handling the statement q = P, where p and q are smart pointers:
- Create a new copyOf the object pointed by P, and have Q point to this copy. This strategy is implemented in copied_ptr.h.
- Ownership Transfer: Let both p and q point to the same object, but transfer the responsibility for cleaning up ("ownership") from P to Q. This strategy is implemented in owned_ptr.h.
- Reference counting: Maintain a count of the smart pointers that point to the same object, and delete the object when this count becomes zero. so the statement q = P causes the count of the object pointed by P to increase by one. this strategy is implemented in counted_ptr.h. scott Meyers offers another reference counting implementation in his book more than tive C ++.
- Reference linking: The same as reference counting, only instead of a count, maintain a circular doubly linked list of all smart pointers that point to the same object. This strategy is implemented in every _ptr.h.
- Copy on write: Use reference counting or linking as long as the pointed object is not modified. When it is about to be modified, copy it and modify the copy. This strategy is implemented in cow_ptr.h.
All these techniques help in the battle against dangling pointers. Each has each own benefits and liabilities.WhichSection of this article discusses the suitability of different smart pointers for varous situations.
Why:Exception safety
Let's take another look at this simple example:
void foo(){ MyClass* p(new MyClass); p->DoSomething(); delete p;}
What happens if dosomething () throws an exception? All the lines after it will not get executed and P will never get deleted! If we're luky, this leads only to memory leaks. however, myclass may free some other resources in its destructor (file handles, threads, transactions, com references, mutexes) and so not calling it my cause severe resource locks.
If we use a smart pointer, however, P will be cleaned up whenever it gets out of scope, whether it was during the normal path of execution or during the stack unwinding caused by throwing an exception.
But isn' t it possible to write exception safe code with regular pointers? Sure, but it is so painful that I doubt anyone actually does this when there is an alternative. Here is what you wocould do in this simple case:
void foo(){ MyClass* p; try { p = new MyClass; p->DoSomething(); delete p; } catch (...) { delete p; throw; }}
Now imagine what wowould happen if we had some if's and for's in there...
Why:Garbage Collection
Since C ++ does not provide automatic garbage collection like some other ages, smart pointers can be used for that purpose. the simplest garbage collection scheme is reference counting or reference linking, but it is quite possible to implement more sophisticated garbage collection schemes with smart pointers. for more information see the garbage collection FAQ.
Why:Efficiency
Smart pointers can be used to make more efficient use of available memory and to shorten allocation and deallocation time.
A common strategy for using memory more efficiently is copy on write (COW ). this means that the same object is shared by your cow pointers as long as it is only read and not modified. when some part of the program tries to modify the object ("write"), the cow pointer creates a new copy of the object and modifies this copy instead of the original object. the standard string class is commonly implemented using cow semantics (see the <string> header ).
string s("Hello");string t = s; // t and s point to the same buffer of characterst += " there!"; // a new buffer is allocated for t before // appending " there!", so s is unchanged.
Optimized allocation schemes are possible when you can make some assumptions about the objects to be allocated or the operating environment. for example, you may know that all the objects will have the same size, or that they will all live in a single thread. although it is possible to implement optimized allocation schemes using class-specific new and delete operators, smart pointers give you the freedom to choose whether to use the optimized scheme for each object, instead of having the scheme set for all objects of a class. it is therefore possible to match the allocation scheme to different operating environments and applications, without modifying the code for the entire class.
Why:
STL containers
The C ++ standard library has des a set of containers and algorithms known as the standard template library (STL). STL is designed to beGeneric(Can be used with any kind of object) andEfficient(Does not incur time overhead compared to alternatives ). to achieve these two design goals, STL containers store their objects by value. this means that if you have an STL container that stores objects of class base, it cannot store of objects of classes derived from base.
class Base { /*...*/ };class Derived : public Base { /*...*/ };Base b;Derived d;vector<Base> v;v.push_back(b); // OKv.push_back(d); // error
What can you do if you need a collection of objects from different classes? The simplest solution is to have a collection of pointers:
vector<Base*> v;v.push_back(new Base); // OKv.push_back(new Derived); // OK too// cleanup:for (vector<Base*>::iterator i = v.begin(); i != v.end(); ++i) delete *i;
The problem with this solution is that after you're done with the container, You need to manually cleanup the objects stored in it. This is both error prone and not exception safe.
Smart pointers are a possible solution, as inclustrated below. (an alternative solution is a smart container, like the one implemented in pointainer. H .)
vector< linked_ptr<Base> > v;v.push_back(new Base); // OKv.push_back(new Derived); // OK too// cleanup is automatic
Since the smart pointer automatically cleans up after itself, there is no need to manually delete the pointed objects.
Note: STL containers may copy and delete their elements behind the scenes (for example, when they resize themselves ). therefore, all copies of an element must be equivalent, or the wrong copy may be the one to keep ve all this copying and deleting. this means that some smart pointers cannot be used within STL containers, specifically the standard auto_ptr and any ownership-transferring pointer. for more info about this issue, see C ++ guru of the week #25.
Which one shoshould I use?
Are you confused enough? Well, this summary shocould help.
Which:Local Variables
The standard auto_ptr is the simplest smart pointer, and it is also, well, standard. if there are no special requirements, you should use it. for local variables, it is usually the right choice.
Which:Class Members
Although you can use auto_ptr as a class member (and save yourself the trouble of freeing objects in the destructor), copying one object to another will nullify the pointer, as your strated below.
class MyClass{ auto_ptr<int> p; // ...};MyClass x;// do some meaningful things with xMyClass y = x; // x.p now has a NULL pointer
Using a copied pointer instead of auto_ptr solves this problem: the Copied object (y) gets a new copy of the member.
Note that using a reference counted or reference linked pointer means 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 and not a simple reference counted/linked pointer.
Which:
STL containers
As explained above, using garbage-collected pointers with STL containers lets you store objects from different classes in the same container.
It is important to consider the characteristics of the specific garbage collection scheme used. specifically, reference counting/linking can leak in the case of circular references (I. E ., when the pointed object itself contains a counted pointer, which points to an object that contains the original counted pointer ). its advantage over other schemes is that it is both simple to implement and deterministic. the deterministic behavior may be important in some real time systems, where you cannot allow the system to suddenly wait while the garbage collector performs its housekeeping duties.
Generally speaking, there are two ways to implement reference counting: intrusive and non-intrusive. intrusive means that the pointed object itself contains the count. therefore, you cannot use intrusive reference counting with 3-rd party classes that do not already have this feature. you can, however, derive a new class from the 3-rd party class and add the count to it. non-Intrusive reference counting requires an allocation of a count for each counted object. the counted_ptr.h is an example of non-intrusive reference counting.
|
|
Reference linking does not require any changes to be made to the pointed objects, nor does it require any additional allocations. A reference linked pointer takes a little more space than a reference counted pointer-just enough to store one or two more pointers. |
|
Both reference counting and reference linking require using locks if the pointers are used by more than one thread of execution.
Which:
Explicit Ownership Transfer
Sometimes, you want to receive a pointer as a function argument, but keep the ownership of this pointer (I. e. the control over its lifetime) to yourself. one way to do this is to use consistent naming-conventions for such cases. taligent's Guide to designing programs recommends using "adopt" to mark that a function adopts ownership of a pointer.
Using an owned pointer as the function argument is an explicit statement that the function is taking ownership of the pointer.
Which:
Big objects
If you have objects that take a lot of space, you can save some of this space by using cow pointers. this way, an object will be copied only when necessary, and shared otherwise. the sharing is implemented using some garbage collection scheme, like reference counting or linking.
Which:Summary
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 |
Conclusion
Smart pointers are useful tools for writing safe and efficient code in C ++. like any tool, they shocould be used with appropriate care, thought and knowledge. for a comprehensive and in depth analysis of the issues concerning smart pointers, I recommend reading Andrei Alexandrescu's chapter about smart pointers in his book Modern C ++ design.
Feel free to use my own smart pointers in your code.
The boost C ++ libraries include some smart pointers, which are more rigorously tested and actively maintained. Do try them first, if they are appropriate for your needs.