Smart Pointers

Smart Pointers

A smart pointer is a class that holds and manages a pointer through a popular C++ technique called “Resource Acquisiton is Initialization” (RAII). It allows developers to not worry about freeing a pointer, and it also allows pointers to be exception-safe.

Ownership

When refering to memory, ownership answers the question: “Who is in charge of freeing the given resource?”

There are three standard smart pointers defined in the <memory> header file:

  • std::unique_ptr<T> A unique pointer does not share ownership, and will free the resource at the end of the scope.
  • std::shared_ptr<T> A shared pointer does share ownership, and will only free the resource when there are no other owners counted and it has reached the end of the scope.
  • std::weak_ptr<T> A weak pointer is used with a shared pointer, but it does not add to the reference counter like a shared pointer does.

Both unique_ptr and shared_ptr have a corresponding function to create their respective pointers:

  • std::make_unique<T>(value) for unique_ptr
  • std::make_shared<T>(value) for shared_ptr

Unique Pointers

Loading...

Shared Pointers

Loading...

Exception Safety

Loading...
Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn C++ on Codecademy