无法以shared_from_this的继承进行编译

Unable to compile with inheritance of shared_from_this

本文关键字:继承 编译 from shared this      更新时间:2023-10-16

我正在使用自制的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<A>转换为派生 通过虚拟底座CEnableSharedFromThis<A>键入 A

所以我尝试以下 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>());
   }
}

覆盖它并改用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