shared_from_this
Shared_from_this
1. 异步模型
1.1 用法
主要用于防止对象过早析构
在 Asio 的异步模型中,调用 async_read 或者 async_write 这种异步操作时,函数会立即返回。当 IO 完成时,Asio 再调用绑定的回调。同时回调可能需要访问 this 的一些成员,但是如果没有任何东西持有 CHttpConnection 的引用,它可能在 I/O 完成前就被析构了!
所以为了解决这个问题,需要在回调中捕获 shared_from_this
1 | |
1.2 原理
shared_from_this() 是 std::enable_shared_from_this<T> 提供的一个成员函数。调用 shared_from_this() 返回的 shared_ptr 与原始 shared_ptr 共享同一块控制块(control block),因此:
- 引用计数 +1;
- 只要还有任何一个
shared_ptr(包括 lambda 捕获的那个self)未被销毁,对象就不会析构;
为什么不直接写 auto self = std::shared_ptr(this);。因为会造成双重析构的风险:
1 | |
这会创建一个全新的、独立的 shared_ptr,它拥有自己的引用计数器。
但 this 已经被另一个 shared_ptr(比如 make_shared 创建的那个)管理了。
→ 当这两个 shared_ptr 各自析构时,都会尝试 delete this,导致 重复释放同一块内存,引发 崩溃或未定义行为。
shared_from_this
https://dxblacksmith.github.io/2026/01/30/shared_from_this/