C++ - "shared_ptr"的使用方法 及 代码

"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; //test
	private:
		//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

 

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值