Modern C++ - Smart pointers

Updated: 2021-05-13

Smart pointers: ensure that programs are free of memory and resource leaks and are exception-safe.

Header file: <memory>

  • unique_ptr: Allows exactly one owner of the underlying pointer. Cannot be copied.
  • shared_ptr: Reference-counted smart pointer. The raw pointer is not deleted until all shared_ptr owners have gone out of scope or have otherwise given up ownership.
  • weak_ptr: provides access to an object that is owned by one or more shared_ptr instances, but does not participate in reference counting. Useful to break circular refernce.

Smart pointers are crucial to the RAII (Resource Acquisition Is Initialization) programming idiom (ensure that resource acquisition occurs at the same time that the object is initialized, so that all resources for the object are created and made ready in one line of code)

std::unique_ptr<A> p(new A());

NOTE: Do not use the new or malloc expression on the smart pointer itself.

Different from Java/C#: no separate garbage collector runs in the background; memory is managed through the standard C++ scoping rules so that the runtime environment is faster and more efficient.

std::make_unique is the new new

(since C++14)

std::unique_ptr<Foo> v = std::make_unique<Foo>();

// or
auto v = std::make_unique<Foo>();