跳到主要内容

std::enable_shared_from_this<T>::operator=

enable_shared_from_this<T>& operator=( const enable_shared_from_this<T> &obj ) noexcept;

什么也不做;返回 *this

参数

obj - 要赋给 *this 的 enable_shared_from_this

返回值

*this

备注

私有的 std::weak_ptr<T> 成员不受此赋值运算符的影响。

示例

注意:enable_shared_from_this::operator= 被定义为 protected,以防止意外的 slicing,同时允许派生类拥有默认的赋值运算符。

#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;
}
结果
4

std::enable_shared_from_this<T>::operator=

enable_shared_from_this<T>& operator=( const enable_shared_from_this<T> &obj ) noexcept;

什么也不做;返回 *this

参数

obj - 要赋给 *this 的 enable_shared_from_this

返回值

*this

备注

私有的 std::weak_ptr<T> 成员不受此赋值运算符的影响。

示例

注意:enable_shared_from_this::operator= 被定义为 protected,以防止意外的 slicing,同时允许派生类拥有默认的赋值运算符。

#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;
}
结果
4