Syntax

C++ is not a memory-managed language. Dynamically allocated memory (i.e. objects created with new) will be “leaked” if it is not explicitly deallocated (with delete). It is the programmer’s responsibility to ensure that the dynamically allocated memory is freed before discarding the last pointer to that object.

Smart pointers can be used to automatically manage the scope of dynamically allocated memory (i.e. when the last pointer reference goes out of scope it is deleted).

Smart pointers are preferred over “raw” pointers in most cases. They make the ownership semantics of dynamically allocated memory explicit, by communicating in their names whether an object is intended to be shared or uniquely owned.

Use #include <memory> to be able to use smart pointers.

Unique ownership (std::unique_ptr)

Sharing ownership std::shared_ptr

Sharing with temporary ownership std::weak_ptr

Using custom deleters to create a wrapper to a C interface

Casting std::shared_ptr pointers

Writing a smart pointer value_ptr

Getting a shared_ptr referring to this

Unique ownership without move semantics std::auto_ptr