C++中shared_ptr的使用
来源:互联网 发布:css书籍推荐 知乎 编辑:程序博客网 时间:2024/05/29 16:52
template class shared_ptr
#include<memory>
shared_ptr是C++ 11之后标准库引入的一个特性,用于简化内存管理,防止内存泄露。
1.shared_ptr的作用是什么?
Objects of shared_ptr types have the ability of taking ownership of a pointer and share that ownership: once they take ownership, the group of owners of a pointer become responsible for its deletion when the last one of them releases that ownership.
注意,这个解释中有两个关键的词语take&&shared the ownership.
2.那么shared_ptr什么时候放弃对ownership的所有权呢?
shared_ptr objects release ownership on the object they co-own as soon as they themselves are destroyed, or as soon as their value changes either by an assignment operation or by an explicit call to shared_ptr::reset. Once allshared_ptr objects that share ownership over a pointer have released this ownership, the managed object is deleted (normally by calling ::delete, but a different deleter may be specified on construction).
3.引用计数的处理:两个shared_ptr指向同一个pointer时,情况如何?
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.
4.empty VS null pointer
shared_ptr that does not own any pointer is called an empty shared_ptr. A shared_ptr that points to no object is called a null shared_ptr and shall not be dereferenced. Notice though that an empty shared_ptr is not necessarily anull shared_ptr, and a null shared_ptr is not necessarily an empty shared_ptr.
5.常用函数
use_count
reset
6.使用实例
#include <iostream>#include <memory>using namespace std;class A{ public: int a; int b; int c; int d;};//16Bstd::shared_ptr<A> test(){ for (int i = 0; i < 1; ++i) { std::shared_ptr<A> pa(new A); return pa; }}int main(int argc, char *argv[]){ for (int i = 0; i < 1000*1000; ++i) { std::shared_ptr<A> pa = test(); cout << pa.use_count(); } while(1); return 0;}
上面是shared_ptr的使用实例,我们可以看到,其中并没有delete操作。我们将shared_ptr换成普通指针,然后利用top命令进行对比,就可以看到二者的所需要的内存大小的不同。
related
[1] weak_ptr
[2] shared_ptr包含在哪些库中?go to shared_ptr
- C++中shared_ptr的使用
- C++11中shared_ptr的使用
- shared_ptr的使用心得
- 使用 shared_ptr 的一個問題代碼
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- 在NDK中使用shared_ptr
- shared_ptr中使用了 FILE* 添加删除器的用法
- shared_ptr 的使用及注意事项
- 使用boost::shared_ptr的教训
- 有关shared_ptr的使用总结
- shared_ptr的使用和陷阱
- shared_ptr的使用和陷阱
- [C++]Shared_ptr使用详解&&实现链表
- shared_ptr使用
- shared_ptr使用
- 使用 shared_ptr
- boost::shared_ptr的多线程使用陷阱
- JDK源码阅读之Runnable接口
- java一些常用代码
- 输入猴子数
- 轻量级分布式服务化框架
- Android Spinner 下拉菜单控件学习
- C++中shared_ptr的使用
- abstract class和interface异同
- 【Linux】Linux软件安装方法小结(附:rpm详解)
- Tomcat startup.bat 能成功启动, Eclipse 里却不能启动Tomcat.
- iOS Frame和bounds的区别
- 干货 | Docker文件系统的分层与隔离
- StringUtil 简单用法
- Climbing Stairs
- Swift 分享多媒体消息到 微信/新浪微博/QQ