使用带有多重继承的enable_shared_from_this

Aar*_*kan 21 c++ multiple-inheritance shared-ptr c++11 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(); 
    }
};
Run Code Online (Sandbox Code Playgroud)

这些用法是否make_shared_from_this()正确,假设它们总是被shared_ptrD 调用?

Off*_*rmo 35

的确,你做错了.如果你有简单的继承,只需从enable_shared_from this基类继承,派生类就可以免费获得它.(当然你需要预测结果)

如果你有多个继承(看起来像),你必须使用这里描述的技巧,也在这里:

/* 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());
  }
};
Run Code Online (Sandbox Code Playgroud)

然后你的代码变成:

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>(); 
    }
};
Run Code Online (Sandbox Code Playgroud)

  • @Offirmo如果我无法修改(继承自inherable_enable_shared_from_this)基类(A、B、C),有没有可能的解决方案? (2认同)