【发布时间】:2012-10-08 23:25:15
【问题描述】:
我有一个派生自 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?
【问题讨论】:
-
我知道 b_ 将与 b 相同,在这种情况下我可以只使用 b。但这只是一个演示;我实际需要使用 shared_from_this 的其他情况会导致相同的错误。
-
在这种情况下,我的解决方案将涉及虚拟继承。我怀疑 boost 可能已经有一个类,可能是
enable_shared_from_this的非模板版本。但如果没有,我会创建我自己的,并在我需要该功能的任何地方从它虚拟继承。当然,您必须使用dynamic_pointer_cast而不是static_pointer_cast。但它会工作。 -
是的 - 我看不到一个明显干净的方法来完成这项工作。它接近于钻石继承,可能表明重新考虑设计是有序的。
标签: c++ boost shared-ptr multiple-inheritance enable-shared-from-this