C++ - "shared_ptr"的使用方法 及 代码
来源:互联网 发布:千方百计医药软件打印 编辑:程序博客网 时间:2024/05/14 10:45
"shared_ptr"的使用方法 及 代码
智能指针(smart pointer)是C++11的新特性. 指针在无人使用时, 自动释放动态内存.
通过"use_count"计数, 并判断是否无人使用, 从而释放内存.
在函数复制(copy)过程中, 默认copy方法是引用相同的潜在元素.
如下代码, b1和b2共享元素, 如果范围结束({}), 则b2释放, b1则没有元素, 为了保持b1中的元素, 而使用动态内存.
由于VS2012很多C++11特性无法支持, 所以在Eclipse CDT上进行测试(GCC4.8.1).
代码(Eclipse CDT)如下, 注意b1的元素个数, 以及shared_pointer的使用数(use_count):
/* * CppPrimer.cpp * * Created on: 2013.11.2 * Author: Caroline *//*eclipse cdt*/#include <iostream>#include <vector>#include <string>#include <initializer_list>#include <memory>#include <stdexcept>using namespace std;class StrBlob {public:typedef std::vector<std::string>::size_type size_type;StrBlob();StrBlob(std::initializer_list<std::string> il);size_type size() const{ return data->size(); }bool empty() const { return data->empty(); }void push_back(const std::string& t) { data->push_back(t); }void pop_back();std::string& front() ;std::string& back() ;std::shared_ptr<std::vector<std::string> > data; //testprivate://std::shared_ptr<std::vector<std::string> > data;void check(size_type i, const std::string &msg) const;};StrBlob::StrBlob():data(std::make_shared<std::vector<std::string>>()) {}StrBlob::StrBlob(std::initializer_list<std::string> il):data(std::make_shared< std::vector<std::string> >(il)) {}void StrBlob::check(size_type i, const std::string &msg) const {if(i >= data->size())throw out_of_range(msg);}std::string& StrBlob::front () {check(0, "front on empty StrBlob");return data->front();}std::string& StrBlob::back () {check(0, "back on empty StrBlob");return data->back();}void StrBlob::pop_back () {check(0, "pop_back on empty StrBlob");data->pop_back();}int main (void) {StrBlob b1;//{}释放b2{StrBlob b2 = {"a", "an", "the"};b1 = b2;b2.push_back("about");}std::cout << "b1 size = " << b1.size() << std::endl;std::cout << "b1 data use count = " << b1.data.use_count() << std::endl;//b2已经被释放了//std::cout << "b2 size = " << b2.size() << std::endl;return 0;}
输出:
b1 size = 4
b1 data use count = 2
- C++ - "shared_ptr"的使用方法 及 代码
- boost::shared_ptr的使用方法
- boost::shared_ptr的使用方法
- boost shared_ptr的使用方法
- boost::shared_ptr的使用方法
- 智能指针 shared_ptr 的使用方法
- DataList的使用方法及代码
- shared_ptr 的使用及注意事项
- 浅谈shared_ptr及shared_ptr涉及到的循环引用问题
- C语言中常用的文件操作函数总结及使用方法演示代码
- 日历控件的代码及使用方法
- 日历控件的代码及使用方法
- 关于boost中shared_ptr使用方法的一些例子
- c++中智能指针auto_ptr与shared_ptr的使用方法
- 让你提前认识软件开发(18):C语言中常用的文件操作函数总结及使用方法演示代码
- 【C/C++】类成员函数地址的获取及使用方法
- 游戏中按概率抽奖的php代码及使用方法
- android github 下载的代码使用方法及问题解决
- FusionMap中国各省份地图无超链接logo
- instancetype 对比 id 的好处。
- OCP-1Z0-053-V12.02-105题
- 不是技术牛人,如何拿到国内IT巨头的Offer
- 新的起点,新的责任
- C++ - "shared_ptr"的使用方法 及 代码
- hdu 2550 百步穿杨
- 继承和组合
- windows + IIS7服务配置
- redis配置文件详解
- libevent源码深度剖析三
- android设置显示语言
- C++在类的成员函数中,允许直接访问该类的成员对象的私有成员变量
- poj 1493 Machined Surfaces