std::enable_shared_from_this<T>:: operator=
From cppreference.net
<
cpp
|
memory
|
enable shared from this
C++
Memory management library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::enable_shared_from_this
| Protected member functions | ||||
|
enable_shared_from_this::operator=
|
||||
| Public member functions | ||||
|
enable_shared_from_this
&
operator
=
(
const
enable_shared_from_this
&
rhs
)
noexcept
;
|
(自 C++11 起) | |
不执行任何操作;返回 * this 。
目录 |
参数
| rhs | - |
要赋值给
*
this
的另一个
enable_shared_from_this
|
返回值
* this
注释
weak_this
不受赋值操作影响。
示例
注意:
enable_shared_from_this
::
operator
=
被定义为
protected
,旨在防止意外的对象切割,同时允许派生类拥有默认的赋值运算符。
运行此代码
#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)
|
具有共享对象所有权语义的智能指针
(类模板) |