【问题标题】:What is the purpose of inheriting from enable_shared_from_this? [duplicate]从 enable_shared_from_this 继承的目的是什么? [复制]
【发布时间】:2018-04-27 09:08:00
【问题描述】:

class Tstd::enable_shared_from_this<T> 继承有什么意义?我似乎不明白你为什么不直接创建一个std::shared_ptr<this>

【问题讨论】:

  • 首先,this 不是一个类型,你不能把它作为模板参数给shared_ptr。那么目的是允许在对象中安全地创建shared_ptrthis

标签: c++11


【解决方案1】:

Cppreference has a good example on why.

如果您想返回this 中的std::shared_ptr,而*this 已经由std::shared_ptr 拥有,并且您不返回shared_from_this(),而是返回一个新的std::shared_ptr<T>(this),那么您将结束有 2 个不知道它们都拥有同一个对象的共享指针,因此 use_count() 将是错误的,这将导致双重 delete,这是未定义的行为。

【讨论】:

    猜你喜欢
    • 2011-05-28
    • 1970-01-01
    • 2016-07-02
    • 2023-01-24
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    相关资源
    最近更新 更多