Namespaces
Variants
Views
Actions

std::unique_ptr::operator=

From cppreference.com
 
 
 
 
 
unique_ptr& operator=( unique_ptr&& r );
(1) (since C++11)
template< class U, class E >
unique_ptr& operator=( unique_ptr<U,E>&& r );
(1) (since C++11)
unique_ptr& operator=( nullptr_t );
(2) (since C++11)

1) Transfers ownership of the object pointed to by r to *this as if by calling reset(r.release()) followed by an assignment from std::forward<E>(r.get_deleter()).

2) Effectively the same as calling reset().

Note that unique_ptr's assignment operator only accepts xvalues, which are typically generated by std::move. (The unique_ptr class explicitly deletes its lvalue copy constructor and lvalue assignment operator.)

Contents

[edit] Parameters

r - smart pointer from which ownership will be transfered

[edit] Return value

*this

[edit] Exceptions

noexcept specification:  
noexcept
  (since C++11)

[edit] Example

#include <iostream>
#include <memory>
 
struct Foo {
    Foo() { std::cout << "Foo\n"; }
    ~Foo() { std::cout << "~Foo\n"; }
};
 
int main() 
{
    std::unique_ptr<Foo> p1;
 
    {
        std::cout << "Creating new Foo...\n";
        std::unique_ptr<Foo> p2(new Foo);
 
        p1 = std::move(p2);
        std::cout << "About to leave inner block...\n";
 
        // Foo instance will continue to live, 
        // despite p2 going out of scope
    }
 
    std::cout << "About to leave program...\n";
}

Output:

Creating new Foo...
Foo
About to leave inner block...
About to leave program...
~Foo