Using Smart Pointers
These three smart pointer templates (auto_ptr
, unique_ptr
, and shared_ptr
) each defines a pointer-like object intended to be assigned an address obtained (directly or indirectly) by new
. When the smart pointer expires, its destructor uses delete
to free the memory. Thus, if you assign an address returned by new
to one of these objects, you don’t have to remember to free the memory later; it will be freed automatically when the smart pointer object expires. Figure 16.2 illustrates the behavioral difference between auto_ptr
and a regular pointer. The shared_ptr
and unique_ptr
share the same behavior in this situation.
To create one of these smart pointer objects, you include ...
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.