bad_weak_ptr的原因

本文介绍了在使用boost::enable_shared_from_this时遇到bad_weak_ptr异常的原因及解决方案,并给出了正确的使用示例。

前几天解了一个bug,表象是调用shared_from_this的时候就跑出bad_weak_ptr异常,类A明明是继承自boost::enable_shared_from_this<A>的,一时搞不明白为什么,后来搜了下出现“bad_weak_ptr异常”可能的原因才找到问题所在:创建类A的对象的时候没有用智能指针包裹,而是直接new的裸指针


【引申】


enable_from_this 的使用与实现原理说明

shared_from_this()是enable_shared_from_this<T>的成员函数,返回shared_ptr<T>;
注意的是,这个函数仅在shared_ptr<T>的构造函数被调用之后才能使用。
原因是enable_shared_from_this::weak_ptr并不在构造函数中设置,而是在shared_ptr<T>的构造函数中设置。


错误的使用代码一

#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <iostream>
using namespace std;

class D: public boost::enable_shared_from_this<D>
{
public:
    D()
    {
        cout<<"D::D()"<<endl;
        boost::shared_ptr<D> p = shared_from_this();
    }    
};

int main()
{
    boost::shared_ptr<D> a(new D);
    return 0;    
}


程序编译通过,执行结果如下:
D::D()
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

说明在D的构造函数中调用shared_from_this(), 此时D的实例本身尚未构造成功,weak_ptr也就尚未设置,所以程序抛出tr1::bad_weak_ptr异常。

错误的使用代码二:

#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <iostream>
using namespace std;

class D: public boost::enable_shared_from_this<D>
{
public:
    D()
    {
        cout<<"D::D()"<<endl;
    }
    
    void func()
    {
        cout<<"D::func()"<<endl;
        boost::shared_ptr<D> p = shared_from_this();
    }    
};

int main()
{
    D d;
    d.func();
    return 0;    
}


程序编译通过,执行结果如下:
D::D()
D::func()
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

失败原因分析:

在主函数main中,D的实例是在栈上构造,没有使用boost::shared_ptr<D> 的构造方式,
所以boost::enable_shared_from_this<D>中的weak_ptr所指的函数对象也就没有被赋值,
在调用d.func()中使用shared_from_this()函数时

----注:shared_from_this的函数实现 ------
shared_ptr<T> shared_from_this()
{
shared_ptr<T> p( weak_this_ );
BOOST_ASSERT( p.get() == this );
return p;
}

----注:shared_from_this的函数实现 ------

调用BOOST_ASSERT( p.get() == this ); 失败,抛出以上异常。


最后,我们给出share_from_this()的正确使用例子:
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <iostream>
using namespace std;

class D: public boost::enable_shared_from_this<D>
{
public:
    D()
    {
        cout<<"D::D()"<<endl;
    }
    
    void func()
    {
        cout<<"D::func()"<<endl;
        boost::shared_ptr<D> p = shared_from_this();
    }    
};

int main()
{
    boost::shared_ptr<D> p(new D);
    p->func();
    return 0;    
}    

执行结果:
D::D()
D::func()


【参考资料:http://blog.chinaunix.net/uid-442138-id-2122464.html】



在 Boost.Asio 的异步编程模型中,`shared_from_this()` 是用于确保对象生命周期的重要工具。为避免因使用不当导致的 `bad_weak_ptr` 异常,需遵循特定的设计模式和调用规则。 当一个类继承自 `boost::enable_shared_from_this` 时,它可以获得指向自身的 `shared_ptr` 实例[^2]。这一机制允许开发者在异步操作中安全地持有当前对象的引用,从而防止对象被提前销毁。然而,在尚未通过 `shared_ptr` 管理的对象上调用 `shared_from_this()` 将引发 `bad_weak_ptr` 异常,因为此时没有有效的共享指针实例与该对象关联。 为了正确使用 `shared_from_this()`,应在创建对象时始终采用 `shared_ptr` 来管理其生命周期。推荐的做法是提供一个静态工厂方法,该方法返回一个 `shared_ptr` 指向新构造的对象实例。例如: ```cpp class udp_server : public boost::enable_shared_from_this<udp_server> { public: static boost::shared_ptr<udp_server> create(boost::asio::io_context& io) { return boost::shared_ptr<udp_server>(new udp_server(io)); } private: udp_server(boost::asio::io_context& io) : socket_(io, udp::endpoint(udp::v4(), 12345)) {} }; ``` 此外,在构造函数内部不应直接启动任何异步操作。由于 `shared_from_this()` 需要对象已经被 `shared_ptr` 所拥有,而在构造函数执行期间这一点可能还未达成,因此在此阶段调用 `shared_from_this()` 可能会抛出异常。正确的做法是在构造完成后显式调用一个启动函数来开始异步处理流程。 当需要将 `this` 作为 `shared_ptr` 传递给异步操作时,应利用 `boost::bind` 或 C++11 的 lambda 表达式捕获 `shared_from_this()` 返回值。这样做可以保证只要异步操作未完成,对象就不会被销毁。以 `async_send_to` 为例,如下所示: ```cpp void do_send() { auto self(shared_from_this()); const std::string& message = send_queue_.front().first; const udp::endpoint& endpoint = send_queue_.front().second; socket_.async_send_to(boost::asio::buffer(message), endpoint, [this, self](const boost::system::error_code& ec, std::size_t /*bytes_sent*/) { std::lock_guard<std::mutex> lock(queue_mutex_); send_queue_.pop_front(); if (!send_queue_.empty()) { do_send(); } }); } ``` 上述代码中,`self` 是从 `shared_from_this()` 获取的 `shared_ptr`,它被绑定到异步操作的完成处理器上。这确保了在回调被执行之前,对象不会被释放。 最后值得注意的是,在多线程环境下进行异步操作时,除了要处理好对象生命周期外,还需考虑线程安全问题。对于共享资源的访问应当采取适当的同步措施,如互斥锁等,以避免数据竞争和其他并发问题。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值