std::unique_ptr

From Cppreference

Jump to: navigation, search
Defined in header <memory>

template<

    class T,
    class Deleter = std::default_delete<T>

> class unique_ptr;
(1) (C++11 feature)
template <

    class T,
    class Deleter

> class unique_ptr<T[],Deleter>;
(2) (C++11 feature)

std::unique_ptr is a smart pointer that retains sole ownership of an object through a pointer. unique_ptr is not copyable or copy-assignable, two instances of unique_ptr cannot manage the same object. A non-const unique_ptr can transfer the onwership of the managed object to another unique_ptr. A const std::unique_ptr cannot be transferred, limiting the lifetime of the managed object to the scope in which the pointer was created. When the unique_ptr is destroyed, it disposes of the object through Deleter.

1) manages the lifetime of a single object, e.g. allocated with new

2) manages the lifetime of an array with a runtime length, e.g. allocated with new[]

Typical uses of std::unique_ptr include

Contents

[edit] Member types

Member type Definition
pointer std::remove_reference<D>::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 new unique_ptr
(public member function)
(destructor)
destructs the managed object if such is present
(public member function)
operator=
assigns the unique_ptr
(public member function)
Modifiers
release
returns a pointer to the managed object and releases the ownership
(public member function)
reset
replaces the managed object
(public member function)
swap
swaps the managed objects
(public member function)
Observers
get
returns a pointer to the managed object
(public member function)
get_deleter
returns the deleter that is used for destruction of the managed object
(public member function)
operator bool
checks if there is associated managed object
(public member function)
Single-object version, unique_ptr<T>
operator*
operator->
dereferences pointer to the managed object
(public member function)
Array version, unique_ptr<T[]>
operator[]
provides indexed access to the managed array
(public member function)

[edit] Non-member functions

operator==
operator!=
operator<
operator<=
operator>
operator>=
compares with another unique_ptr or with nullptr
(function template)
std::swap(std::unique_ptr) (C++11)
specializes the std::swap() algorithm
(function template)

[edit] Helper classes

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