std::enable_shared_from_this<T>::operator=
来自cppreference.com
| (C++11 起) (C++26 起为 constexpr) |
||
不做任何事:weak_this 不受赋值影响。
参数
| rhs | - | 赋值给 *this 的另一 enable_shared_from_this
|
返回值
*this
注解
将 operator= 定义为 protected 是为了在避免意外切片的同时允许派生类拥有默认的赋值运算符。
示例
Run this code
#include <iostream>
#include <memory>
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;
// 两个赋值运算符都使用 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() << '\n';
}
输出:
4
参阅
(C++11) |
拥有共享对象所有权语义的智能指针 (类模板) |