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