0

多くの場合、次のように asio イベント キューを見つけます。

handler_that_destroys_object()
handler_that_acts_on_object()

私は現在、オブジェクトを共有ポインターに格納し、handler_that_acts_on_object() でそのオブジェクトへの弱いポインターを使用することで、これを回避しています。

私はこれが好きではありません。なぜなら、共有ポインターを使用したくない場所で強制的に使用するからです。

オブジェクトの所有者に共有ポインタを強制的に回避するより良い方法はありますか?

たとえば、オブジェクトのアロケーターで共有ポインターの使用が強制されないように、オブジェクト自体内のオブジェクトにある種の共有カウントを使用します。

私が欲しいのは、暗黙の参照カウントとしてオブジェクトの存在を伴う、weak_ptr と shared_from_this のようなものです。

アップデート

これも私が望むように機能するようです(おそらく良い方法ではありませんが、私が望むことを説明するためだけです)

#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/noncopyable.hpp>

struct SelfCounting
    : boost::shared_ptr<SelfCounting>
//  , boost::noncopyable<SelfCounting> /* Does not work */
{
    int d;
};

BOOST_AUTO_TEST_CASE(SelfCounting_automatic) {
    boost::weak_ptr<SelfCounting> p;
    {
        SelfCounting t;
        p = boost::shared_ptr<SelfCounting>(t);
    }
    BOOST_CHECK(!p.lock());
}

BOOST_AUTO_TEST_CASE(SelfCounting_boost_sp) {
    boost::weak_ptr<SelfCounting> p;
    {
        boost::shared_ptr<SelfCounting> t(new SelfCounting());
        p = boost::shared_ptr<SelfCounting>(t);
    }
    BOOST_CHECK(!p.lock());
}

おそらく問題がありますが、valgrind から何の不満もなく動作します。

4

0 に答える 0