C++11 introduces new smart pointers: std::unique_ptr, std::shared_ptr, std::weak_ptr. std::auto_ptr now becomes deprecated and then eventually removed in C++17.
std::unique_ptr is a non-copyable, movable pointer that manages its own heap-allocated memory. Note: Prefer using the std::make_X helper functions as opposed to using constructors. See the sections for std::make_unique and std::make_shared.
std::unique_ptr<Foo> p1 { new Foo{} }; // `p1` owns `Foo`
if (p1) {
p1->bar();
}
{
std::unique_ptr<Foo> p2 {std::move(p1)}; // Now `p2` owns `Foo`
f(*p2);
p1 = std::move(p2); // Ownership returns to `p1` -- `p2` gets destroyed
}
if (p1) {
p1->bar();
}
// `Foo` instance is destroyed when `p1` goes out of scope
A std::shared_ptr is a smart pointer that manages a resource that is shared across multiple owners. A shared pointer holds a control block which has a few components such as the managed object and a reference counter. All control block access is thread-safe, however, manipulating the managed object itself is not thread-safe.
void foo(std::shared_ptr<T> t) {
// Do something with `t`...
}
void bar(std::shared_ptr<T> t) {
// Do something with `t`...
}
void baz(std::shared_ptr<T> t) {
// Do something with `t`...
}
std::shared_ptr<T> p1 {new T{}};
// Perhaps these take place in another threads?
foo(p1);
bar(p1);
baz(p1);