std::enable_shared_from_this<T>::operator=
來自 cppreference.com
< cpp | memory | enable shared from this
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
以防止意外的切片(slicing),但允許派生類擁有預設的賦值運算子。
執行此程式碼
#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; // 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() << '\n'; }
輸出
4
[編輯] 參閱
(C++11) |
具有共享物件所有權語義的智慧指標 (類模板) |