C++11 智能指针之 std::shared_ptr 初级学习
2016-07-11 22:44
531 查看
shared_ptr概念
shared_ptr基于“引用计数”模型实现,多个shared_ptr可指向同一个动态对象,并维护了一个共享的引用计数器,记录了引用同一对象的shared_ptr实例的数量。当最后一个指向动态对象的shared_ptr销毁时,会自动销毁其所指对象(通过delete操作符)。shared_ptr的默认能力是管理动态内存,但支持自定义的Deleter以实现个性化的资源释放动作。
shared_ptr的创建
std:make_shared 方式std:shared_ptr<std:string> a = std:make_shared<std:string>("hello");
构造函数方式
std:shared_ptr<std:string> a(new std:string("hello"));
简单测试代码
#include <iostream> #include <memory> using namespace std; class A{ private: int x; public: A(int x):x(x){} void print() { cout<<"x="<<x<<endl; } ~A() { cout<<"x="<<x<<" deleted"<<endl; } }; class B { public: void testB(shared_ptr<A> a) { cout<<"fourth count="<<a.use_count()<<endl; a->print(); } }; void testA(shared_ptr<A> a) { cout<<"testA count="<<a.use_count()<<endl; a->print(); } shared_ptr<A> testC() { shared_ptr<A> a = make_shared<A>(2); return a; } void testD(shared_ptr<A> &a) { cout<<"testD count="<<a.use_count()<<endl; a->print(); } int main() { shared_ptr<A> a(new A(1)); { a->print(); cout<<"first count="<<a.use_count()<<endl; shared_ptr<A> aa = a; cout<<"second count="<<a.use_count()<<endl; cout<<"second count="<<aa.use_count()<<endl; testA(a); cout<<"after testA count="<<a.use_count()<<endl; B c; c.testB(a); } cout<<"first over count="<<a.use_count()<<endl; shared_ptr<A> b = testC(); cout<<"after testC count="<<b.use_count()<<endl; testD(b); return 0; }
输出结果
可以看到shared_ptr作为形参的时候(testA和testB)use_count会增加1,但退出函数后回到原来的use_count,但作为引用传递的时候(testD)并不会增加use_count
相关文章推荐
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- C++11的for循环,以及范围Range类的简单实现
- 在 Qt4 中使用 C++11
- c++11新特性--decltype auto
- centos安装devtoolset-3支持gcc 4.9.2
- c++11学习笔记
- 使用eclipse编译含有C++11特性的代码
- 怎样在Linux环境编译支持C11
- eclipse支持c++11
- C++11可变参数函数与for循环
- vs2013 编译c++是发现惊天bug
- 简单性能测试函数模板
- 关于C++现状的一些思考
- 用C++11优化矩阵运算的空间和时间效率
- c++11之regex:初识regex
- 浅析构造函数之默认构造函数
- C++11新特性学习笔记
- c++中返回数组的函数
- C++函数重载的几个问题
- C++11 note-2 字符串 容器 迭代器