public member function
<memory>

std::shared_ptr::operator=

copy (1)
shared_ptr& operator= (const shared_ptr& x) noexcept;template <class U> shared_ptr& operator= (const shared_ptr<U>& x) noexcept;
move (2)
shared_ptr& operator= (shared_ptr&& x) noexcept;template <class U> shared_ptr& operator= (shared_ptr<U>&& x) noexcept;
move from (3)
template <class U> shared_ptr& operator= (auto_ptr<U>&& x);template <class U, class D> shared_ptr& operator= (unique_ptr<U,D>&& x);
shared_ptr assignment
The copy assignments (1) adds the object as a shared owner of x's assets, increasing their use_count.

The move assignments (2) transfer ownership from x to the shared_ptr object without altering the use_count. x becomes an empty shared_ptr (as if default-constructed).

Likewise, the move assignments from other managed pointer types (3) also transfer ownership, and are initialized with set a use count of 1.

Additionally, in all cases above, a call to this function has the same side effects as if shared_ptr's destructor was called before its value changed (including the deletion of the managed object if this shared_ptr was unique).

You cannot assign the value of a pointer directly to a shared_ptr object. You may either use make_shared or member reset instead.

Parameters

x
An object of a managed pointer type.
U* shall be implicitly convertible to T* (where T is shared_ptr's template parameter).

Return value

*this

Example

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

int main () {
  std::shared_ptr<int> foo;
  std::shared_ptr<int> bar (new int(10));

  foo = bar;                          // copy

  bar = std::make_shared<int> (20);   // move

  std::unique_ptr<int> unique (new int(30));
  foo = std::move(unique);            // move from unique_ptr

  std::cout << "*foo: " << *foo << '\n';
  std::cout << "*bar: " << *bar << '\n';

  return 0;
}

Output:
*foo: 30
*bar: 20


See also