为何会有enable_share_from_this

这几天看到了这个东西,一直很疑惑这是干嘛的,看到stackoverflow上面的一个大牛的解释,原话如下:


The key point is that the "obvious" technique of just returning shared_ptr(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 p(new X());

此时,若我们

shared_ptr q = p;

我们很自然地知道了,new X()生成的指针对象只会在p和q都死掉(生命周期结束)之后才会析构一次.


当如果是这样呢?

X* p = new X();

shared_ptr a(p);

shared_ptr b(p);

很显然,此时不出意外程序是会出错的,p指向的堆被重复析构了,在a和b死掉的时候delete p都会被调用.


同样的

class X {

shared_ptr getX()

{

shared_ptr r(this);

return r;

}

};


shared_ptr p(new X());

X& a = *p;

shared_ptr 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)