您的位置:首页 > 编程语言 > C语言/C++

C++Primer学习:智能指针与动态内存(2)

2015-10-14 15:12 387 查看

unique_ptr,它也是一种智能指针,但是某个时候只能有一个指向unique_ptr指向一个给定对象.

//定义并初始化

unique_ptr<int > p(new int(42));


p = nullptr;//释放
p.release();//放弃对指针的控制,返回指针.但是不释放所指对象
p.reset();//释放所指对象
p.reset(q);//释放所指对象,提供内置指针q,并令p指向这个对象
p.reset(nullptr);


weak_ptr是一种不控制对象生存周期的智能指针,它指向一个由shared_ptr管理的对象;当最后一个指向对象的shared_ptr被销毁,对象就会被释放,即时还有weak_ptr指向对象.它提供了reset(),lock(),expired()等成员函数来控制.

练习:定义一个StrBlob的伴随指针类:StrBlobPtr,它保存一个weak_ptr,指向StrBlob的data成员.通过使用weak_ptr,不会影响一个给定的StrBlob所指的vector的生存周期.它还保存了一个curr,用来保存当前所指对象的下标.此外,还在StrBlob中增加了begin(),end()成员用来返回一个指向它自己的StrBlobPtr类.

class StrBlobPtr;
class StrBlob
{
friend class StrBlobPtr;
public:
//构造函数
StrBlob() :data(std::make_shared<vector<string>>()) {};//默认初始化
StrBlob(initializer_list<string>il) : data(make_shared<vector<string>>(il)){};
size_t size()const { return data->size(); };
bool empty() const { return data->empty(); }
void push_back(const string & s) { data->push_back(s); };
void pop_back() { check(0, "pop_back on empty StrBlob"); data->pop_back(); };
string & front(){ check(0, "front on empty strblob"); return data->front(); };
string & back(){ "back on empty strblob"; return data->back(); };
const string & front()const{ "front on empty strblob"; return data->front(); };
const string & back()const{ "back on empty strblob"; return data->back(); };
StrBlobPtr begin();//定义成员函数
StrBlobPtr end();//定义成员函数

private:
shared_ptr<vector<string>>data;//智能指针
void check(size_t , const string&)const;
};
void StrBlob:: check(size_t i, const string&msg)const
{
if (i >= data->size())
throw out_of_range(msg);
}

class StrBlob;
class  StrBlobPtr
{
public:
StrBlobPtr() :curr(0){};
StrBlobPtr(StrBlob & a, size_t sz = 0) :wptr(a.data), curr(sz){};
string & deref() const;
StrBlobPtr& incr();

private:
weak_ptr<vector<string>> wptr;
size_t curr;//定义下标
shared_ptr<vector<string>> check(size_t, const string&)const;
};
shared_ptr<vector<string>> StrBlobPtr::check(size_t i, const string& msg) const
{
auto ret = wptr.lock();
if (!ret)
throw::runtime_error("unbound StrBlobPtr");//未绑定的weak_ptr
if (i >= ret->size())
throw::out_of_range("msg");
return ret;
}
string& StrBlobPtr::deref() const
{
auto ret = check(curr, "deference past end");
return (*ret)[curr];
}
StrBlobPtr& StrBlobPtr::incr()
{
check(curr, "increment past end of StrBolbPtr");
++curr;
return *this;
}
//定义StrBlob的成员函数begin(),end()
StrBlobPtr StrBlob::begin()
{
return StrBlobPtr(*this);
}
StrBlobPtr StrBlob::end()
{
return StrBlobPtr(*this, data->size());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: