enable_share_from_this功能介绍

https://blog.csdn.net/csfreebird/article/details/8282518

 

这个类很有意思,让一个被shared_ptr管理生命周期的类能够在自己的成员函数内部访问shared_ptr。有点绕。

举个例子,下面的代码在函数f内部通过this构造了shared_ptr对象,然后打印x_的值。

 

 
  1. class B {

  2. public:

  3. B(): x_(4) {

  4. cout << "B::B()" << endl;

  5. }

  6.  
  7. ~B() {

  8. cout << "B::~B()" << endl;

  9. }

  10.  
  11. void f() {

  12. shared_ptr<B> p(this);

  13. cout << p->x_ << endl;

  14. //shared_from_this();

  15. }

  16.  
  17. private:

  18. int x_;

  19. };

  20.  
  21.  
  22. /*

  23. *

  24. */

  25. int main(int argc, char** argv) {

  26. shared_ptr<B> x(new B);

  27. x->f();

  28. return 0;

  29. }

编译通过,但是运行结果:

 

 

 
  1. B::B()

  2. 4

  3. B::~B()

  4. B::~B()

两次析构B对象,这是个灾难。
现在试一下enable_shared_from_this:

 

 

 
  1. class A : public enable_shared_from_this<A> {

  2. public:

  3. A() {

  4. cout << "A::A()" << endl;

  5. }

  6.  
  7. ~A() {

  8. cout << "A::~A()" << endl;

  9. }

  10.  
  11. void f() {

  12. //cout << shared_from_this()->x_ << endl; // this way is okay too

  13. shared_ptr<A> p = shared_from_this();

  14. cout << p->x_ << endl;

  15. }

  16.  
  17. private:

  18. int x_;

  19. };

  20.  
  21.  
  22. /*

  23. *

  24. */

  25. int main(int argc, char** argv) {

  26. shared_ptr<A> x(new A);

  27. x->f();

  28. return 0;

  29. }

运行结果:

 

 

 
  1. A::A()

  2. 0

  3. A::~A()

那么,为什么需要这样做呢?在自己的类里面访问自己的成员,其实只是个示例代码,一定必要都没有。

不过有一种可能,就是f函数需要返回自己的指针给调用者,难道这样写么?

 

A* f();

一个裸指针返回出去,失控了。谁也不知道调用者会干什么?

 

比较聪明的方法是设计成:

shared_ptr<A> f()

好了,这就是为什么我们需要enable_shared_from_this。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值