我有一个派生自 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
在给定的继承链中不止一次。
在这种情况下,你可以离开基类A
继承自 enable_shared_from_this
, 并且有派生类 B
返回 shared_ptr<A>
然后 static_pointer_cast
它到shared_ptr<B>
.
或者正如 Omnifarious 指出的那样,您可以在 B
中拥有一个函数这是为你做的。虽然,而不是重载 shared_from_this()
我更喜欢明确命名的函数,以尽量减少类客户的意外:
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
class A : public boost::enable_shared_from_this<A> { };
class B : public A {
public:
using enable_shared_from_this<A>::shared_from_this;
shared_ptr<B> shared_B_from_this() {
return boost::static_pointer_cast<B>(shared_from_this());
}
shared_ptr<B const> shared_B_from_this() const {
return boost::static_pointer_cast<B const>(shared_from_this());
}
};
int main() {
shared_ptr<B> b = shared_ptr<B>(new B);
shared_ptr<B> b1 = boost::static_pointer_cast<B>(b->shared_from_this());
shared_ptr<B> b2 = b->shared_B_from_this();
return 0;
}
关于c++ - 当基类和派生类都继承自 boost::enable_shared_from_this 时出现错误的弱指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12790859/