std::unique_ptr - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::unique_ptr

From cppreference.com
< cpp‎ | memory

Defined in header `<memory>` |  |
template< class T, class Deleter = std::default_delete<T> > class unique_ptr; | (1) | (since C++11)
template < class T, class Deleter > class unique_ptr<T[], Deleter>; | (2) | (since C++11)

`std::unique_ptr` is a smart pointer that retains sole ownership of an object through a pointer and destroys that object when the `unique_ptr` goes out of scope. No two `unique_ptr` instances can manage the same object.

The object is destroyed and its memory deallocated when either of the following happens:

- `unique_ptr` managing the object is destroyed
- `unique_ptr` managing the object is assigned another pointer via operator= or reset().

The object is destroyed using a potentially user-supplied deleter by calling Deleter(ptr). The deleter calls the destructor of the object and dispenses the memory.

A `unique_ptr` may also own no objects, in which case it is called empty.

There are two versions of `std::unique_ptr`:

1) Manages the lifetime of a single object (e.g. allocated with new)
2) Manages the lifetime of a dynamically-allocated array of objects (e.g. allocated with new[])

The class satisfies the requirements of `MoveConstructible` and `MoveAssignable`, but not the requirements of either `CopyConstructible` or `CopyAssignable`.

Type requirements
- `Deleter` must be `FunctionObject` or lvalue reference to a `FunctionObject` or lvalue reference to function, callable with an argument of type `unique_ptr<T, Deleter>::pointer`

### [edit] Notes

Only non-const `unique_ptr` can transfer the ownership of the managed object to another `unique_ptr`. The lifetime of an object managed by const std::unique_ptr is limited to the scope in which the pointer was created.

Typical uses of `std::unique_ptr` include:

- providing exception safety to classes and functions that handle objects with dynamic lifetime, by guaranteeing deletion on both normal exit and exit through exception

- passing ownership of uniquely-owned objects with dynamic lifetime into functions

- acquiring ownership of uniquely-owned objects with dynamic lifetime from functions

- as the element type in move-aware containers, such as std::vector, which hold pointers to dynamically-allocated objects (e.g. if polymorphic behavior is desired)

`std::unique_ptr` may be constructed for an incomplete type `T`, such as to facilitate the use as a handle in the Pimpl idiom. If the default deleter is used, `T` must be complete at the point in code where the deleter is invoked, which happens in the destructor, move assignment operator, and `reset` member function of `std::unique_ptr`. (Conversely, std::shared_ptr can't be constructed from a raw pointer to incomplete type, but can be destroyed where `T` is incomplete.)

### [edit] Member types

Member type | Definition
pointer | std::remove_reference<Deleter>::type::pointer if that type exists, otherwise T*
element_type | `T`, the type of the object managed by this `unique_ptr`
deleter_type | `Deleter`, the function object or lvalue reference to function or to function object, to be called from the destructor

### [edit] Member functions

(constructor) | constructs a new `unique_ptr` (public member function) [edit]
(destructor) | destructs the managed object if such is present (public member function) [edit]
operator= | assigns the `unique_ptr` (public member function) [edit]
##### Modifiers
release | returns a pointer to the managed object and releases the ownership (public member function) [edit]
reset | replaces the managed object (public member function) [edit]
swap | swaps the managed objects (public member function) [edit]
##### Observers
get | returns a pointer to the managed object (public member function) [edit]
get_deleter | returns the deleter that is used for destruction of the managed object (public member function) [edit]
operator bool | checks if there is associated managed object (public member function) [edit]
##### Single-object version, `unique_ptr<T>`
operator*operator-> | dereferences pointer to the managed object (public member function) [edit]
##### Array version, `unique_ptr<T[]>`
operator[] | provides indexed access to the managed array (public member function) [edit]

### [edit] Non-member functions

make_unique (C++14) | creates a unique pointer that manages a new object (function template) [edit]
operator==operator!=operator<operator<=operator>operator>= | compares to another `unique_ptr` or with nullptr (function template) [edit]
std::swap(std::unique_ptr) (C++11) | specializes the std::swap algorithm (function template) [edit]

### [edit] Helper classes

std::hash<std::unique_ptr> (C++11) | hash support for std::unique_ptr (class template specialization) [edit]

### [edit] Example

Run this code

    #include <iostream>
    #include <memory>

    struct Foo
    {
        Foo()      { std::cout << "Foo::Foo\n";  }
        ~Foo()     { std::cout << "Foo::~Foo\n"; }
        void bar() { std::cout << "Foo::bar\n";  }
    };

    void f(const Foo &)
    {
        std::cout << "f(const Foo&)\n";
    }

    int main()
    {
        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
            std::cout << "destroying p2...\n";
        }

        if (p1) p1->bar();

        // Foo instance is destroyed when p1 goes out of scope
    }

Output:

    Foo::Foo
    Foo::bar
    f(const Foo&)
    destroying p2...
    Foo::bar
    Foo::~Foo

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/memory/unique_ptr&oldid=70071"