我有一个基类,它派生自boost::enable_shared_from_this,还有另一个类,它同时派生自基类和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
什么导致了这个问题,有没有什么解决办法?
编辑:
如果我需要像这样的东西:
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。
enable_shared_from_this
的非模板版本。但如果没有,我会创建自己的类,并在需要该功能的任何地方进行虚拟继承。当然,你必须使用dynamic_pointer_cast
而不是static_pointer_cast
。但它会起作用。 - Omnifarious