坏弱指针,当基类和派生类无论是从提升继承:: enable_shared_from_this [英] bad weak pointer when base and derived class both inherit from boost::enable_shared_from_this

查看:216
本文介绍了坏弱指针,当基类和派生类无论是从提升继承:: enable_shared_from_this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类,它从boost :: enable_shared_from_this派生,然后另一类来自基类和boost :: enable_shared_from_this派生:

I have a base class which derives from boost::enable_shared_from_this, and then another class which derives from both the base class and boost::enable_shared_from_this:

#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>

using namespace boost;

class A : public enable_shared_from_this<A> { };

class B : public A , public enable_shared_from_this<B> {
public:
    using enable_shared_from_this<B>::shared_from_this;
};

int main() {
shared_ptr<B> b = shared_ptr<B>(new B());
shared_ptr<B> b_ = b->shared_from_this();

return 0;
}

这编译但在运行时它给

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> >'
  what():  tr1::bad_weak_ptr
Aborted

是什么原因造成这一点,是有它周围的一些方法?

What is causing this, and is there some way around it?

编辑:

如果我需要这样的事是什么:

What if I need something like this:

class A : public enable_shared_from_this<A> { };
class B : public enable_shared_from_this<B> { };    

class C : public A, public B, public enable_shared_from_this<C> {
public:
    using enable_shared_from_this<C>::shared_from_this;
};

这样A和B都需要对自己shared_from_this(和一个不​​能从其他继承它),和C需要A,B和shared_from_this?

such that A and B both need shared_from_this on their own (and one can't inherit it from the other), and C needs A, B, and shared_from_this?

推荐答案

下面是我会怎么解决你的问题:

Here's how I would solve your problem:

#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>

using namespace boost;

class virt_enable_shared_from_this :
   public enable_shared_from_this<virt_enable_shared_from_this>
{
 public:
   virtual ~virt_enable_shared_from_this() {}
};

template <class T>
class my_enable_shared_from_this : virtual public virt_enable_shared_from_this
{
 public:
   shared_ptr<T> shared_from_this() {
      return dynamic_pointer_cast<T>(virt_enable_shared_from_this::shared_from_this());
   }
};

class A : public my_enable_shared_from_this<A> { };

class B : public my_enable_shared_from_this<B> { };

class C : public A, public B, public my_enable_shared_from_this<C> {
 public:
   using my_enable_shared_from_this<C>::shared_from_this;
};

int main() {
   shared_ptr<C> c = shared_ptr<C>(new C());
   shared_ptr<C> c_ = c->shared_from_this();

   return 0;
}

这是痛苦的,至少有点难看。但它的工作原理相当不错,时尚了。我觉得弗雷泽的重新思考你的设计理念很可能是更好的选择。

This is painful and at least a bit ugly. But it works reasonably well, after a fashion. I think Fraser's idea of re-thinking your design is likely the better option.

这篇关于坏弱指针,当基类和派生类无论是从提升继承:: enable_shared_from_this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆