SMART POINTERS

Smart pointers are objects of a template type that behave like pointers but are different — well, they are smart. If you use a smart pointer when you allocate heap memory, the smart pointer will take care of deleting it for. Using smart pointers means never having to use delete. You can also store smart pointers in an STL container, as you’ll see.

Smart pointers come in three flavors. The memory header defines the following types in the std namespace that represent smart pointers:

  • unique_ptr<T> is a type that defines an object that stores a pointer of which there can be only one. Assigning or copying a unique_ptr<T> object is not possible. The pointer stored by one unique_ptr<T> object can be moved to another using std::move(). After such an operation the original object will be invalid.
  • shared_ptr<T> is a type that stores a pointer to an object, but several shared_ptr objects can point to the same object and the number of shared_ptr objects that reference the object is recorded. All shared_ptr objects for a given T that reference the same pointer must be destroyed before the object that they all point to can be deleted. When the last of the shared_ptr objects pointing to a given object dies, the object to which it points will be destroyed and the memory released.
  • weak_ptr<T> is a type that also stores a pointer that is reference counted, but the existence of weak_ptr objects that point to a given object does not prevent the object from being destroyed and its memory ...

Get Ivor Horton's Beginning Visual C++ 2012 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.