Smart pointers¶
Standard pointers, or raw pointers, in C++ do not indicate ownership: a
pointer does not tell you who owns the object the pointer is referring to, who
should delete it and how. In C++11, so called smart pointers, which wrap
around raw pointers, where introduced to overcome these limitations. They are
contained in the <memory>
header; an alternative implementation ships with
Boost and is commonly used within the IceCube software framework.
There are three different types of smart pointers:
Exclusive ownership:
unique_ptr
,Shared ownership:
shared_ptr
,Cyclic references: break cycles with
weak_ptr
.
Exclusive ownership¶
The unique_ptr
provides the semantics of strict ownership: it owns the
object it is referring to.
// initialize smart pointer with a raw pointer
std::unique_ptr<double> p{new double{42.}};
The memory allocated for the double above is automatically released once the pointer expires (goes out of scope). One consequence of C++’s definition of strict ownership is that unique pointers cannot be copied, only moved.
Note
Unique pointers accept a custom deleter class as a second template parameter, which is called to destroy the owned object.
Recommendations¶
Prefer unique pointers to shared pointers.
Prefer ordinary scoped objects to objects on the heap owned by a unique pointer.