public member function
<memory>

std::unique_ptr::operator=

move assignment (1)
unique_ptr& operator= (unique_ptr&& x) noexcept;
assign null pointer (2)
unique_ptr& operator= (nullptr_t) noexcept;
type-cast assignment (3)
template <class U, class E>
  unique_ptr& operator= (unique_ptr<U,E>&& x) noexcept;
copy assignment (deleted!) (4)
unique_ptr& operator= (const unique_ptr&) = delete;
unique_ptr assignment
The object acquires the ownership of x's content, including both the stored pointer and the stored deleter (along with the responsibility of deleting the object at some point). Any object owned by the unique_ptr object before the call is deleted (as if unique_ptr's destructor was called).

If the argument is a null pointer (2), the unique_ptr object becomes empty, with the same behavior as if calling:
 
reset();


Otherwise, it acquires x's assets, with a behavior equivalent to:
1
2
reset(u.release());
get_deleter() = forward<deleter_type>(u.get_deleter());


If the deleter_type is a reference type, the deleter object is copied (instead of moved).

The assignment operation between unique_ptr objects that point to different types (3) needs to be between types whose pointers are implicitly convertible, and shall not involve arrays in any case (the third signature is not part of the array specialization of unique_ptr).

Copy assignment (4) to a unique_ptr type is not allowed (deleted signature).

After a call to lhs=rhs (where both lhs and rhs represent compatible unique_ptr objects):
  • lhs owns the data previously owned by rhs and has rhs's former stored pointer and stored deleter.
  • The data owned by lhs before the call has been deleted (using the deleter that member get_deleter would provide before the call).
  • rhs is empty, owning no data and pointing to nullptr.

Parameters

x
A unique_ptr rvalue.
U* shall be implicitly convertible to T* (where T is unique_ptr's first template parameter).
Notice that this function only performs move assignment. Copy assignment is not supported by unique_ptr (except for nullptr).

Return value

*this

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// unique_ptr::operator= example
#include <iostream>
#include <memory>

int main () {
  std::unique_ptr<int> foo;
  std::unique_ptr<int> bar;

  foo = std::unique_ptr<int>(new int (101));  // rvalue

  bar = std::move(foo);                       // using std::move

  std::cout << "foo: ";
  if (foo) std::cout << *foo << '\n'; else std::cout << "empty\n";

  std::cout << "bar: ";
  if (bar) std::cout << *bar << '\n'; else std::cout << "empty\n";

  return 0;
}


Output:
foo: empty
bar: 101

See also