实现一个strBlob类,通过智能指针,这个类的对象间共享数据data
//动态内存实例StrBlob
class StrBlob
{
public:
typedef vector<string>::size_type size_type;
StrBlob();
StrBlob(initializer_list<string> il);
size_type size() const { return data->size(); }
bool empty() const { return data->empty(); }
//添加删除元素
void push_back(const string &t) { data->push_back(t); }
void pop_back();
//元素访问
string &front();
string &back();
~StrBlob();
private:
// 智能指针对象
shared_ptr<vector<string>> data;
void check(size_type i, const string &msg) const;
};
// 默认构造函数,make_shared创建一个智能指针
StrBlob::StrBlob():data(make_shared<vector<string>>())
{
}
StrBlob::StrBlob(initializer_list<string> il): data(make_shared<vector<string>>(il))
{
}
void StrBlob::pop_back()
{
check(0, "pop_back on empty StrBlob");
data->pop_back();
}
string & StrBlob::front()
{
check(0, "front on empty StrBlob");
return data->front();
}
string & StrBlob::back()
{
check(0, "back on empty StrBlob");
return data->back();
}
StrBlob::~StrBlob()
{
}
void StrBlob::check(size_type i, const string & msg) const
{
if (i >= data->size()) {
throw out_of_range(msg);
}
}
调用
int main()
{
StrBlob b1;
StrBlob b2 = { "a","an","the" };
b1 = b2;
b2.push_back("about");
cout << "b1:" << b1.size();
cout << "b2:" << b2.size();
return 0;
}
输出都为4
动态内存
动态内存实现vector创建和读写
vector<int>* newVector() {
vector<int> *vec=new vector<int>();
return vec;
}
vector<int>* makeVector(vector<int>* vec) {
int a;
while(cin>>a)
{
vec->push_back(a);
}
return vec;
}
void getVector(vector<int>* vec) {
for (vector<int>::iterator it = vec->begin(); it != vec->end(); it++)
cout << *it << " "; //使用迭代器,正确
delete vec;
}
int main()
{
getVector(makeVector(newVector()));
return 0;
}
智能指针
不需要delete操作
shared_ptr<vector<int>> newVector() {
shared_ptr<vector<int>> vec = make_shared<vector<int>>();
return vec;
}
shared_ptr<vector<int>> makeVector(shared_ptr<vector<int>> vec) {
int a;
while(cin>>a)
{
vec->push_back(a);
}
return vec;
}
void getVector(shared_ptr<vector<int>> vec) {
for (vector<int>::iterator it = vec->begin(); it != vec->end(); it++)
cout << *it << " "; //使用迭代器,正确
}
int main()
{
getVector(makeVector(newVector()));
return 0;
}