std::enable_shared_from_this::operator=

From cppreference.com
 
 
Utilities library
Type support (basic types, RTTI, type traits)
Dynamic memory management
Error handling
Program utilities
Variadic functions
Date and time
Function objects
(C++11)
Relational operators
Optional and any
(C++17)
(C++17)
Pairs and tuples
(C++11)
(C++17)
Swap, forward and move
(C++14)
(C++11)
(C++11)
Type operations
(C++11)
(C++17)
 
 
 
enable_shared_from_this<T>& operator=( const enable_shared_from_this<T> &obj );
(since C++11)

Does nothing; returns *this.

Contents

[edit] Parameters

obj - an enable_shared_from_this to assign to *this

[edit] Return value

*this

[edit] Exceptions

noexcept specification:  
noexcept
  

[edit] Notes

The private std::weak_ptr<T> member is not affected by this assignment operator.

[edit] Example

Note: enable_shared_from_this::operator= is defined as protected in order to prevent accidental slicing but allow derived classes to have default assignment operators.

#include <memory>
#include <iostream>
 
class SharedInt : public std::enable_shared_from_this<SharedInt>
{
public:
    explicit SharedInt(int n) : mNumber(n) {}
    SharedInt(const SharedInt&) = default;
    SharedInt(SharedInt&&) = default;
    ~SharedInt() = default;
 
    // Both assignment operators use enable_shared_from_this::operator=
    SharedInt& operator=(const SharedInt&) = default;
    SharedInt& operator=(SharedInt&&) = default;
 
    int number() const { return mNumber; }
 
private:
    int mNumber;
};
 
int main() {
    std::shared_ptr<SharedInt> a = std::make_shared<SharedInt>(2);
    std::shared_ptr<SharedInt> b = std::make_shared<SharedInt>(4);
    *a = *b;
 
    std::cout << a->number() << std::endl;
}

Output:

4

[edit] See also

(C++11)
smart pointer with shared object ownership semantics
(class template)