c++ - 无法通过shared_from_this的继承进行编译

标签 c++ compiler-errors shared-ptr

我正在使用自制的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()方法。

编译器说:

error: cannot convert from base CEnableSharedFromThis<A> to derived type A via virtual base CEnableSharedFromThis<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());
   }
}

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

关于c++ - 无法通过shared_from_this的继承进行编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30805150/

相关文章:

c++ - 什么是 C++ 的最佳开放 XML 解析器?

c++ - C memcmp 第三个参数类型

c++ - 为什么调用基类析构函数会导致程序崩溃?

c++ - 使用 std::tr1::shared_ptr 作为引用计数的内部机制

c# - C++ 17 中的 std::byte 是否等同于 C# 中的字节?

c++ - 初学者模板编译错误 - 无法将函数作为 arg 传递

java - 制作俄罗斯方 block 游戏时出现编译错误

c++ - 从模板类切换时,为什么出现<错误类型>?

c++ - 为什么在 shared_ptr 只取一个时 unique_ptr 取两个模板参数?

STL 容器中的 C++11 shared_pointer constness