c++ - 当基类和派生类都继承自 boost::enable_shared_from_this 时出现错误的弱指针

标签 c++ boost shared-ptr multiple-inheritance enable-shared-from-this

我有一个派生自 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/

相关文章:

c++ - 如何将 CAPI 的 CryptImportKey 与来自 OpenSSL 的 PEM 编码公钥一起使用?

c++ - 使用 initialization_list 导致歧义的函数重载

c++ - auto_ptr 或 shared_ptr

c++ - 没有用于方法调用的可行的 std::weak_ptr 到 std::shared_ptr 的转换

c++ - 如何在 Windows 7 64 位下使用 AddMonitor() 添加 redmonnt.dll

c++ - 不同类型气候条件的颜色编码背景

c++ - 链接 libcurl 问题

c++ - 使用 Microsoft Visual Studio 8 在 boost 中编译 BJAM 1.33.1

c++ - 如何使用 boost C++ 开始单元测试

c++ - 使用 vector<char> 作为缓冲区而不在 resize() 上初始化它