为何会有enable_share_from_this
2016-10-04 11:08
204 查看
这几天看到了这个东西,一直很疑惑这是干嘛的,看到stackoverflow上面的一个大牛的解释,原话如下:
The key point is that the "obvious" technique of just returning shared_ptr<Y>(this) is broken, because this winds up creating
multiple distinct shared_ptr objects with separate reference counts. For this reason you must never create more than one shared_ptr from
the same raw pointer
结合自己的理解,解说一下:
shared_ptr有两种构成方法,从原始指针转换过来,通过其他的shared_ptr生成.
后面一种我们知道,这也是shared_ptr存在的核心意义所在.前面一种我们也必须用过.
比如:
shared_ptr<X> p(new X());
此时,若我们
shared_ptr<X> q = p;
我们很自然地知道了,new X()生成的指针对象只会在p和q都死掉(生命周期结束)之后才会析构一次.
当如果是这样呢?
X* p = new X();
shared_ptr<X> a(p);
shared_ptr<X> b(p);
很显然,此时不出意外程序是会出错的,p指向的堆被重复析构了,在a和b死掉的时候delete p都会被调用.
同样的
class X {
shared_ptr<X> getX()
{
shared_ptr<X> r(this);
return r;
}
};
shared_ptr<X> p(new X());
X& a = *p;
shared_ptr<X> q = a.getX();
同理,此时new X()的指针对象将会被重复析构.
q的构成此时直接越过了p的管辖,从原始指针再次生成一个shared_ptr.
enable_share_from_this就可以解决上面的问题......
http://blog.csdn.net/yuxiaohen/article/details/9235111
The key point is that the "obvious" technique of just returning shared_ptr<Y>(this) is broken, because this winds up creating
multiple distinct shared_ptr objects with separate reference counts. For this reason you must never create more than one shared_ptr from
the same raw pointer
结合自己的理解,解说一下:
shared_ptr有两种构成方法,从原始指针转换过来,通过其他的shared_ptr生成.
后面一种我们知道,这也是shared_ptr存在的核心意义所在.前面一种我们也必须用过.
比如:
shared_ptr<X> p(new X());
此时,若我们
shared_ptr<X> q = p;
我们很自然地知道了,new X()生成的指针对象只会在p和q都死掉(生命周期结束)之后才会析构一次.
当如果是这样呢?
X* p = new X();
shared_ptr<X> a(p);
shared_ptr<X> b(p);
很显然,此时不出意外程序是会出错的,p指向的堆被重复析构了,在a和b死掉的时候delete p都会被调用.
同样的
class X {
shared_ptr<X> getX()
{
shared_ptr<X> r(this);
return r;
}
};
shared_ptr<X> p(new X());
X& a = *p;
shared_ptr<X> q = a.getX();
同理,此时new X()的指针对象将会被重复析构.
q的构成此时直接越过了p的管辖,从原始指针再次生成一个shared_ptr.
enable_share_from_this就可以解决上面的问题......
http://blog.csdn.net/yuxiaohen/article/details/9235111
相关文章推荐
- 为何会有enable_share_from_this
- 为何会有enable_share_from_this
- enable_share_from_this
- enable_share_from_this功能介绍
- enable_share_from_this 模板类使用和完全解析
- enable_share_from_this功能介绍
- enable_share_from_this
- enable_share_from_this功能介绍
- enable_share_from_this功能介绍
- enable_share_from_this
- share_ptr 与enable_shared_from_this
- <C++>shared_ptrs利用std::enable_shared_from_this()实现安全管理this指针
- 为什么使用enable_shared_from_this——shared_ptr两类错误
- 关于std::shared_ptr与std::enable_shared_from_this循环引用导致的问题
- This application is currently offline. To enable the application, remove the app_offline.htm file from the application root dire
- boost::enable_shared_from_this的部分实现研究
- Multiple Inheritance and enable_shared_from_this
- share_from_this
- C++11新特性之十一:enable_shared_from_this
- C++学习 std::tr1::shared_ptr、std::tr1::weak_ptr及std::tr1::enable_shared_from_this