c++ - 使用带有多重继承的enable_shared_from_this

标签 c++ c++11 shared-ptr multiple-inheritance enable-shared-from-this

BI 在我的代码中使用 enable_shared_from_this,但我不确定其用法是否正确。这是代码:

class A: public std::enable_shared_from_this<A>
{
public:
    void foo1()
    {
        auto ptr = shared_from_this(); 
    }
};

class B:public std::enable_shared_from_this<B>
{
public:
    void foo2()
    {
        auto ptr = shared_from_this(); 
    }
};

class C:public std::enable_shared_from_this<C>
{
public:
    void foo3()
    {
        auto ptr = shared_from_this(); 
    }
};

class D: public A, public B, public C
{
public:
    void foo()
    {
        auto ptr = A::shared_from_this(); 
    }
};

假设总是通过 D 的 shared_ptr 调用 make_shared_from_this() 的这些用法是否正确?

最佳答案

确实你做错了。如果你有简单的继承,只需在基类中继承enable_shared_from this,派生类就可以免费获得它。 (当然你需要对结果进行向下转换)

如果你有多重继承(就像看起来的那样),你必须使用描述的技巧 here还有here :

/* Trick to allow multiple inheritance of objects
 * inheriting shared_from_this.
 * cf. https://stackoverflow.com/a/12793989/587407
 */

/* First a common base class
 * of course, one should always virtually inherit from it.
 */
class MultipleInheritableEnableSharedFromThis
: public std::enable_shared_from_this<MultipleInheritableEnableSharedFromThis> {
public:
  virtual ~MultipleInheritableEnableSharedFromThis()
  {}
};

template <class T>
class inheritable_enable_shared_from_this
: virtual public MultipleInheritableEnableSharedFromThis {
public:
  std::shared_ptr<T> shared_from_this() {
    return std::dynamic_pointer_cast<T>(
        MultipleInheritableEnableSharedFromThis::shared_from_this()
    );
  }
  /* Utility method to easily downcast.
   * Useful when a child doesn't inherit directly from enable_shared_from_this
   * but wants to use the feature.
   */
  template <class Down>
  std::shared_ptr<Down> downcasted_shared_from_this() {
    return std::dynamic_pointer_cast<Down>(
       MultipleInheritableEnableSharedFromThis::shared_from_this()
    );
  }
};

然后你的代码变成:

class A: public inheritable_enable_shared_from_this<A>
{
public:
    void foo1()
    {
        auto ptr = shared_from_this(); 
    }
};

class B: public inheritable_enable_shared_from_this<B>
{
public:
    void foo2()
    {
        auto ptr = shared_from_this(); 
    }
};

class C: public inheritable_enable_shared_from_this<C>
{
public:
    void foo3()
    {
        auto ptr = shared_from_this(); 
    }
};

class D: public A, public B, public C
{
public:
    void foo()
    {
        auto ptr = A::downcasted_shared_from_this<D>(); 
    }
};

关于c++ - 使用带有多重继承的enable_shared_from_this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16082785/

相关文章:

c++ - 亚信 : usage of self shared pointer in the examples

c++ - std::move weak_ptr::lock 的返回值弄乱了 shared_ptr 的引用计数?

c++ - C++中被调用函数的异常处理

c++ - DX11 最小缓冲区大小

c++ - 静态方法返回类的 shared_ptr

c++ - 返回 lambda 表达式的方法中的转换错误

c++ - 复制构造函数...出了什么问题?

时间:2019-03-08 标签:c++wcfclientduplex

c++ - 有没有办法从仿函数中提取第一个参数的类型?

c++ - 带有初始化器的 lambda 是否等同于没有初始化器的 lambda?