【问题标题】:tr1::bad_weak_ptr [duplicate]tr1::bad_weak_ptr [重复]
【发布时间】:2011-06-09 07:07:28
【问题描述】:

可能重复:
enable_shared_from_this - empty internal weak pointer?

AuthConnection::AuthConnection(boost::asio::io_service& io_service)
    :Connection(io_service)
{
    boost::shared_ptr<AuthHandler>h (new AuthHandler( shared_from_this() ));
    this->handler=h;
}

shared_from_this() 应该返回 Connection 的 ptr,但它抛出了这个异常

tr1::bad_weak_ptr

我不知道这里出了什么问题!

【问题讨论】:

    标签: c++ boost-asio shared-ptr


    【解决方案1】:

    我猜你对shared_from_this() 的使用是错误的。

    应该在一个类中使用如下:

    class Y: public enable_shared_from_this<Y>
    {
    public:
    
        shared_ptr<Y> f()
        {
            return shared_from_this();
        }
    }
    

    然后就可以调用y-&gt;f()获取类的this指针了。

    不仅仅是这个,实际问题在this问答中解释。这与您不能在派生对象的ctor中调用shared_from_this()这一事实有关。

    【讨论】:

    • 我测试了它并且同样的错误,注意是从它那里开车所以我真的不需要一种方法来获取 ptr
    • @Mixed 我在答案中添加了一些内容。
    • 所以我做了boost::shared_ptr&lt;Connection&gt; con=this-&gt;getThis(); boost::shared_ptr&lt;AuthHandler&gt;h (new AuthHandler(con)); 仍然是同样的错误,还是我弄错了!?
    • @MixedCoder 我们不知道ConnectionAuthConnectionAuthHandler之间的关系是什么;我们不知道“notice that aredriving from it”(原文如此)中的 it 是什么,我们甚至也不知道我们在 哪里应该注意到它。至此,您应该期待心灵小队的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多