liveBook · Manning

Smart pointer

As explained in Learn C++ by Example

A smart pointer is a C++ library type that manages an object pointer and can automate ownership and storage cleanup.

A smart pointer is a C++ library type that manages an object pointer and helps automate ownership and storage cleanup. It reduces the need to pair every allocation with a manual delete. section 1.1 section 6.2.1

Smart pointers become especially useful when a program stores objects of different derived types together. A vector of smart pointers can refer to objects sharing a common base type while preserving their differing behavior through polymorphism. section 6.0 section 6.2.1

The practical advantage appears when managing polymorphic objects:

  • Raw pointers can support the required virtual-method behavior, but their objects must be deleted by hand. section 6.2.1
  • Manual cleanup becomes harder when references might go out of scope too soon or an exception interrupts the program. section 6.2.1
  • Smart pointers address these cleanup challenges while allowing different blob types to compete through a shared interface. section 6.0 section 6.2.1

A polymorphic blob race

A race contains stepper blobs and randomly moving blobs. Because both derive from a common Blob type, a vector of smart pointers can hold them together; virtual methods then make each blob move according to its own implementation. The smart pointers remove the need to delete every blob pointer manually when the race ends or fails with an exception. section 6.0 section 6.2.1

How Learn C++ by Example covers it

How deep it goes
Explains the cleanup problem and polymorphic role, but does not distinguish smart-pointer varieties or detail ownership semantics.
Examples
Uses a race containing stepper and randomly moving Blob objects as the central example.
What it assumes
Assumes inheritance, common base types, pointers or references, virtual methods, and object lifetime concerns.
What you can do after
Apply smart pointers to store varied derived objects safely in a polymorphic collection.
How it connects
Connects smart pointers with inheritance, virtual methods, dynamic polymorphism, vectors, object lifetime, exceptions, and memory management.

Also explained in

Compare how 5 books explain smart pointer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.