使用boost::enable_shared_from_this的注意事项

本文详细介绍了在C++中使用boost::enable_shared_from_this的注意事项,包括必须使用shared_ptr来管理对象,并且不能在构造函数或析构函数中调用shared_from_this()方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文转载于:http://blog.sina.com.cn/s/blog_5f435c130101hpzi.html

[转自]lemonClover的日记

http://www.douban.com/note/180325584/

使用boost::enable_shared_from_this的注意事项

2011-10-26 16:44:26
 1. 如果一个类继承了boost::enable_shared_from_this,那么之后创建这个类的对象的时候,一定要用shared_ptr封装起来。
 2. 一定不要在构造函数和析构函数里面调用shared_from_this(),否则会引起十分诡异的错误。

 昨天就是因为在析构函数里面调用了另一个函数,而这个函数里面使用了shared_from_this(),导致运行时出现bad_weak_ptr的错误,调试了一个晚上和一个上午才发现。

【原因分析】

为什么不能在构造函数中调用shared_from_this

namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace net = boost::asio; // from <boost/asio.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> using TypeCallbackClientOnDone = std::function<void(const char*, const std::string&, const char*)>; // Performs an HTTP GET and prints the response class ClientSession : public std::enable_shared_from_this<ClientSession> { public: // Objects are constructed with a strand to // ensure that handlers do not execute concurrently. explicit ClientSession(net::io_context& ioc, std::shared_ptr<beast::tcp_stream> stream, const std::string& host, int port); // Start the asynchronous operation void Run(int timeout, char const* target, const char* contentType, const std::string& content, const TypeCallbackClientOnDone& cb); // 拿走其内的Stream std::shared_ptr<beast::tcp_stream> TakeStream(); private: void DoRun(int timeout, const std::string& target, const std::string& contentType, const std::string& content, const TypeCallbackClientOnDone& cb); void OnConnect(beast::error_code* ecPtr, int timeout); void OnWrite(beast::error_code ec, std::size_t bytes_transferred, int timeout); void OnRead(beast::error_code ec, std::size_t bytes_transferred, int timeout); void OnFail(const std::string& errMsg, char const* what); void ReportFail(const std::string& errMsg, char const* what); void CloseSocketAndConnect(int timeout); private: net::io_context& ioc_; std::shared_ptr<beast::tcp_stream> stream_; std::string host_; int port_{ 0 }; //用于底层连接复用,是否失败时重连 bool reconnect_{ true }; beast::flat_buffer buffer_; // (Must persist between reads) http::request<http::string_body> request_; http::response<http::string_body> res_; TypeCallbackClientOnDone funcOnDone_; }; 改用strand序列化
07-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值