std::shared_ptr
生活随笔
收集整理的這篇文章主要介紹了
std::shared_ptr
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*auto_ptr:會發生語義轉移,不支持應用計數
scoped_ptr:不支持復制,只有自己可以管理指針
scoped_array:支持數組
shared_ptr:最好的智能指針,支持引用計數,容器操作等,復制指針時引用計數加一,當復制的對象析構時引用計數減1,當引用計數為0是析構對象
*/#include <memory>
#include <iostream>
using namespace std;
class shared
{
private:shared_ptr<int> p;
public:shared(shared_ptr<int> _p):p(_p){}void print(){cout << "count:" << p.use_count() << "v = " << *p << endl; }
};void print_func(shared_ptr<int> p)
{cout << "count:" << p.use_count() << "v = " << *p << endl;
}//退出函數時,p自動析構,引用計數減1int main()
{shared_ptr<int> p(new int(100));shared s1(p);{shared s2(p);s2.print();//3
}s1.print();//2*p = 20;print_func(p);//3s1.print();//2
getchar();
}
//我一直想知道shared_ptr和auto_ptr什么區別,現在總算清楚了
//我一直想知道shared_ptr和auto_ptr什么區別,現在總算清楚了
總結
以上是生活随笔為你收集整理的std::shared_ptr的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET MVC中使用Fluent
- 下一篇: GLSL实现HDR Rendering