shared_ptr

int *ptr=new int(1);
      7         shared_ptr<int> p1(ptr);
      8         shared_ptr<int> p2(ptr);
      9         cout<<p1.use_count();
     10         cout<<p2.use_count();

上面的写法是错误的,因为shared_ptr objects can only share ownership by copying their value: If two shared_ptr are constructed (or made) from the same (non-shared_ptr) pointer, they will both be owning the pointer without sharing it, causing potential access problems when one of them releases it (deleting its managed object) and leaving the other pointing to an invalid location.

 

可以将shared_ptr用于vector中

1.vector<shared_ptr<T>> vector中的元素指针设定为shared_ptr类型,这样的话,在析够vector时就不需要手动delete指针

  

vector<shared_ptr<test>> pVec;
test *t=new test(1);
shared_ptr<test> t1(t);
pVec.push_back(t1);
pVec.push_back(shared_ptr<test>(new test(2)));

这样到函数的最后,自动调用test的析够函数。

  

2.shared_ptr<vector<T>>

  列举下用法:shared_ptr<std::vector<int>> vecInt(new std::vector<int>)

shared_ptr还得继续

贴一个不错的博客:

http://www.cnblogs.com/xiaoxinxd/archive/2013/02/26/shared_ptr_20130226.html

posted on 2013-11-14 22:48  Practicer..  阅读(396)  评论(0编辑  收藏  举报

导航