【问题标题】:Unable to compile with inheritance of shared_from_this无法使用 shared_from_this 的继承进行编译
【发布时间】:2015-06-12 14:10:06
【问题描述】:

我正在使用自制的 shared_from_this 类 (CEnableSharedFromThis),因为我在 C++03 下,无法在我的项目中使用 boost。

我有一个 A 类,看起来像这样:

class A : virtual CEnableSharedFromThis<A>
{
...
}

和这样的 B 类:

class B : public A, virtual CEnableSharedFromThis<A>
{
   void foo()
   {
      Poco::SharedPtr<B> b(sharedFromthis());
   }
}

我看到有些人使用模棱两可的方法有错误。所以我使用虚拟继承,我没有这个错误。

但是我在 foo() 方法中有一个我不能放弃的新方法。

编译器说:

错误:无法从基础 CEnableSharedFromThis&lt;A&gt; 转换为派生 通过虚拟基础输入A CEnableSharedFromThis&lt;A&gt;

所以我尝试了以下 foo() 方法:

   void foo()
   {
      Poco::SharedPtr<B> b(B::sharedFromthis());
   }

但它什么也没改变。

有什么想法吗?

编辑:

根据您的建议,我删除了 B 的 CEnableSharedFromThis 的继承,并像这样更改 foo() 函数:

class B : public A
{
   void foo()
   {
      Poco::SharedPtr<B> b(sharedFromthis().cast<B>());
   }
}

【问题讨论】:

  • 不应该是class B : public A, virtual CEnableSharedFromThis&lt;B&gt;吗?
  • @m.s.但是虚拟继承会做什么呢?它们是完全不同的类,不是吗?
  • 根本不需要虚拟继承(AB 都不是)。只有A 应该从CEnableSharedFromThis 继承(参见this SO question);如果您有多重继承,则需要虚拟继承(请参阅this SO question
  • 在我的情况下,调用者必须获取 B 的实例而不是 A。所以如果我从 B 的 CEnableSharedFromThis 中删除继承,我只会得到 A 的 shardePtr 而不是 B
  • 你可以使用 static_pointer_cast 来投射指针。

标签: c++ compiler-errors shared-ptr


【解决方案1】:

覆盖它并改用 static_pointer_cast。

class B : public A
{
   Poco::SharedPtr<B> sharedFromThis() {
       return Poco::StaticPointerCast<B>(CEnableSharedFromThis<A>::sharedFromThis());
   }
   void foo()
   {
      Poco::SharedPtr<B> b(sharedFromthis());
   }
}

这是假设存在与std::static_pointer_cast 类似的Poco::StaticPointerCast

【讨论】:

    猜你喜欢
    • 2015-04-24
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 2019-05-22
    • 1970-01-01
    • 2017-01-15
    相关资源
    最近更新 更多