Smart Pointers
Smart pointers are one of the most important additions to C++ because they empower you to implement explicit memory management in C++. Beside the deprecated std::auto_ptr
, C++ offers three different smart pointers. They are defined in the header <memory>
.
Firstly there is the std::unique_ptr
, which models the concept of exclusive ownership. Secondly, there is the std::shared_ptr
, who models the concept of shared ownership. Lastly, there is the std::weak_ptr
. std::weak_ptr
is not so smart, because it has only a thin interface. Its job is it to break cycles of std::shared_ptr
. It models the concept of temporary ownership.
The smart pointers manage their resource according to the RAII idiom. So the resource is automatically released if the smart pointer goes out of scope.