Shared Ownership of Dynamic Variables
Prior to C++11, a more limited smart pointer called
auto_ptr<> was available in the standard library. Among the many limitations of the
auto_ptr<> template class was the fact that it could not be used as the element type in C++ standard library container classes or to transfer ownership of a dynamic variable out of a function. The standard library contained a reference-counted smart pointer class called
shared_ptr<> that could be used in function arguments, return values, and standard library containers. For a few years, some teams used
shared_ptr<> exclusively and forbade the use of raw pointers.
The problem with
shared_ptr<> is that it is expensive in terms of runtime instructions. In addition to the dynamic variable that
shared_ptr<> owns, it creates a second dynamic variable to hold a reference count, as shown in Figure 7.8, and deletes the reference count when the last reference is deleted. Every...