StrBlob类——智能指针作为成员

/*	
	管理string的类
	使用vector来管理元素
	由于类对象被销毁时相应的元素成员也将销毁
	所以需要将vector保存在动态内存中 
*/
//该程序鲁棒性不强,没有考虑到vector为空的情况 
#include <iostream> 
#include <memory>
#include <vector>
#include <string>

using namespace std;

class StrBlob {
	using size_type = vector<string>::size_type;
public:
	StrBlob() :spVec(make_shared<vector<string>>()) {}
	StrBlob(initializer_list<string> il) :spVec(make_shared<vector<string>>(il)) {}
	size_type size() const { return spVec->size(); }
	size_type capacity() const { return spVec->capacity(); }
	const string& front() const { return spVec->front(); }
	const string& back() const { return spVec->back(); }
	void push_back(const string &s) { spVec->push_back(s); }
	void pop_back() { spVec->pop_back(); }
private:
	shared_ptr<vector<string>> spVec;
}; 

int main()
{
	StrBlob b1;
	StrBlob b2{"i", "love", "kzw"};
	b1 = b2;
	b2.push_back("always");			//修改b2指向的vector,但由于 
	cout << b1.back() << endl;		//b1和b2指向相同的vector,故会打印always 
}

优势:即使StrBlob类对象被销毁,vector并不一定会被销毁!

适用:多个类对象间共享数据

posted @ 2017-11-17 17:51  GGBeng  阅读(389)  评论(0编辑  收藏  举报