enable_shared_from_this
1. 为什么要有enable_shared_from_this
StackOverflow上的一个回答比较精炼:“当你只有一个this指针的时候,它(enable_shared_from_this)可以让你获得一份指向this的shared_ptr实例”。
It enables you to get a valid shared_ptr instance to this, when all you have is this. Without it, you would have no way of getting a shared_ptr to this, unless you already had one as a member.
比较常见的一个误解时,你都有this指针了,获取shared_ptr岂不是易如反掌?
struct A { void func() { // only have "this" ptr ? } }; // func內只有this可用,此时想获得一个指向它的shared_ptr void func() { std::shared_ptr<A> local_sp_a(this); // do something with local_sp_a }
问题是,这个local_sp_a是新生成的智能指针,跟已有的指向this的指针没有关联上,有两份引用计数。这会导致重复释放。
2. 使用方法
struct A : public enable_shared_from_this<A> { void func() { std::shared_ptr<A> local_sp_a = shared_from_this(); // do something with local_sp } };
有几个需要注意的地方:
- public继承
- enable_shared_from_this是个模板
- 头文件 memory
- 获取sp的方法是shared_from_this
3. 如何实现的
enable_shared_from_this<T>内部会留存一份std::weak_ptr<T>成员,在调用shared_from_this时,会从weak_ptr安全的生成一个自身的shared_ptr。
TODO:探索一下实现的代码。
4. 参考
https://en.cppreference.com/w/cpp/memory/enable_shared_from_this
https://stackoverflow.com/questions/712279/what-is-the-usefulness-of-enable-shared-from-this
https://www.zhihu.com/question/30957800
https://www.jianshu.com/p/4444923d79bd

浙公网安备 33010602011771号