Modern C++ Design

(From Ch. 7, Smart Pointers)

Smart pointers may manage ownership in various ways, each appropriate to a category of problems. Some smart pointers transfer ownership automatically: After you copy a smart pointer to an object, the source smart pointer becomes null, and the destination points to (and holds ownership of) the object. This is the behavior implemented by the standard-provided std::auto_ptr. Other smart pointers implement reference counting: They track the total count of smart pointers that point to the same object, and when this count goes down to zero, they delete the pointed-to object. Finally, some others duplicate their pointed-to object whenever you copy them.

In short, in the smart pointers' world, ownership is an important topic. By providing ownership management, smart pointers are able to support integrity guarantees and full value semantics. Because ownership has much to do with constructing, copying, and destroying smart pointers, it's easy to figure out that these are the most vital functions of a smart pointer.

The following few sections discuss various aspects of smart pointer design and implementation. The goal is to render smart pointers as close to raw pointers as possible, but not closer. It's a contradictory goal: After all, if your smart pointers behave exactly like dumb pointers, they are dumb pointers.

In implementing compatibility between smart pointers and raw pointers, there is a thin line between nicely filling compatibility checklists and paving the way to chaos. You will find that adding seemingly worthwhile features might expose the clients to costly risks. Much of the craft of implementing good smart pointers consists of carefully balancing their set of features. [...]

[read this chapter for free]
[Table of Contents]

Home > Books > Modern C++ Design

Modern C++ Design

This book has forever changed all aspects of software design and implementation using the C++ programming language. To this day it is an authoritative guide to advanced design techniques and their realization in C++.



  • Due to lack of experience, Andrei was initially afraid to work alone on the the book so he proposed co-authorship to Scott Meyers. Andrei would provide the designs and the code and Scott would do the writeup. Scott insisted that Andrei raises up to the task, warmly recommended him to Addison Wesley, and mentored him throughout. The two ended up becoming longtime friends.
  • At publication time not all code was compilable with existing compilers, and different compilers accepted different subsets of the code. Andrei compiled certain snippets "on paper" by perusing the C++ standard document.
  • "Compiles all of Loki" became an informal yardstick for C++ compilers. Compiler vendors took notice and improved their compilers accordingly.