6

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 を必要とするように?

4

2 に答える 2

10

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;
}
于 2012-10-09T00:10:02.043 に答える