std::enable_shared_from_this::operator=

enable_shared_from_this<T>& operator=( const enable_shared_from_this<T> &obj ) noexcept;
(C++11 起)

不做任何事;返回 *this

目录

参数

obj - 赋值给 *thisenable_shared_from_this

返回值

*this

注意

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

示例

注意:定义 enable_shared_from_this::operator= 为受保护以避免意外切片,但允许导出类拥有默认的赋值运算符。

#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;
 
    // 两个赋值运算符都使用 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

参阅

(C++11)
拥有共享对象所有权语义的智能指针
(类模板)

版本历史

  • (当前 | 先前 2017年9月9日 (六) 07:47Fruderica讨论 | 贡献. . (1,581字节) (+479). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 17:56P12bot讨论 | 贡献 . . (1,102字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:03P12bot讨论 | 贡献 . . (1,102字节) (-74). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 16:22P12bot讨论 | 贡献 . . (1,176字节) (+417). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 03:25P12讨论 | 贡献 . . (759字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (759字节) (-41). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:09P12讨论 | 贡献 . . (800字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (800字节) (+800). . (Translated from the English version using Google Translate)