C++Smart Pointers


Syntax

  • std::shared_ptr<ClassType> variableName = std::make_shared<ClassType>(arg1, arg2, ...);
  • std::shared_ptr<ClassType> variableName (new ClassType(arg1, arg2, ...));
  • std::unique_ptr<ClassType> variableName = std::make_unique<ClassType>(arg1, arg2, ...); // C++14
  • std::unique_ptr<ClassType> variableName (new ClassType(arg1, arg2, ...));

Remarks

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.