157
7
Smart Pointers
Hecatombs of code and rivers of ink have been dedicated to smart pointers by program-
mers and writers around the world. Perhaps the most popular, intricate, and powerful
C idiom, smart pointers are interesting in that they combine many syntactic and se-
mantic issues. This chapter discusses smart pointers, from their simplest aspects to their
most complex ones and from the most obvious errors in implementing them to the subtlest
ones—some of which also happen to be the most gruesome.
In brief, smart pointers are C objects that simulate simple pointers by implement-
ing operator-> and the unary operator*. In addition to sporting pointer syntax and
semantics, smart pointers often perform useful tasks—such as memory management or
locking—under the covers, thus freeing the application from carefully managing the life-
time of pointed-to objects.
This chapter not only discusses smart pointers but also implements a SmartPtr class
template. SmartPtr is designed around policies (see Chapter 1), and the result is a smart
pointer that has the exact levels of safety, efficiency, and ease of use that you want.
After reading this chapter, you will be an expert in smart pointer issues such as the
following:
• The advantages and disadvantages of smart pointers
• Ownership management strategies
• Implicit conversions
• Tests and comparisons
• Multithreading issues
This chapter implements a generic SmartPtr class template. Each section presents one
implementation issue in isolation. At the end, the implementation puts all the pieces to-
gether. In addition to understanding the design rationale of SmartPtr, you will know how
to use, tweak, and extend it.
7.1 Smart Pointers 101
So what’s a smart pointer? A smart pointer is a C class that mimics a regular pointer
in syntax and some semantics, but it does more. Because smart pointers to different type
07-A1568 01/23/2001 12:38 PM Page 157