六一的部落格


关关难过关关过,前路漫漫亦灿灿。




StrBlobPtr


声明

 1class StrBlobPtr
 2{
 3    public:
 4        StrBlobPtr() : curr(0) { }
 5        StrBlobPtr(StrBlob &a, size_t sz = 0) : wptr(a.data), curr(sz) { }
 6
 7        string& deref() const;  // 获取当前元素的引用
 8        StrBlobPtr& incr();     // 更新下标,返回自己
 9
10    private:
11        shared_ptr<vector<string>> check(size_t, const string&) const;
12        weak_ptr<vector<string>> wptr;
13
14        size_t curr;
15};

实现

 1// 做两件事:检查sp是否仍有效;检查下标是否越界
 2shared_ptr<vector<string>> StrBlobPtr::check(size_t i, const string &msg) const
 3{
 4    auto ret = wptr.lock();
 5    if (!ret)
 6        throw runtime_error("unbound StrBlobPtr");
 7    if (i >= ret->size())
 8        throw out_of_range(msg);
 9    return ret;
10}
11
12string &StrBlobPtr::deref() const
13{
14    auto p = check(curr, "dereference past end");
15    return (*p)[curr];
16}
17
18StrBlobPtr &StrBlobPtr::incr()
19{
20    check(curr, "increment past end of StrBlobPtr");
21    ++curr;
22    return *this;
23}

StrBlob


声明

 1class StrBlobPtr;
 2
 3class StrBlob
 4{
 5    friend class StrBlobPtr; // StrBlobPtr会访问StrBlob的data
 6
 7public:
 8    // ...
 9    StrBlobPtr begin() { return StrBlobPtr(*this); }
10    StrBlobPtr end() {
11        auto ret = StrBlobPtr(*this, data->size());
12        return ret;
13    }
14};

使用StrBlobPtr访问StrBlob



StrBlobPtr


声明

 1class StrBlobPtr
 2{
 3    public:
 4        StrBlobPtr() : curr(0) { }
 5        StrBlobPtr(StrBlob &a, size_t sz = 0) : wptr(a.data), curr(sz) { }
 6
 7        string& deref() const;  // 获取当前元素的引用
 8        StrBlobPtr& incr();     // 更新下标,返回自己
 9
10    private:
11        shared_ptr<vector<string>> check(size_t, const string&) const;
12        weak_ptr<vector<string>> wptr;
13
14        size_t curr;
15};

实现

 1// 做两件事:检查sp是否仍有效;检查下标是否越界
 2shared_ptr<vector<string>> StrBlobPtr::check(size_t i, const string &msg) const
 3{
 4    auto ret = wptr.lock();
 5    if (!ret)
 6        throw runtime_error("unbound StrBlobPtr");
 7    if (i >= ret->size())
 8        throw out_of_range(msg);
 9    return ret;
10}
11
12string &StrBlobPtr::deref() const
13{
14    auto p = check(curr, "dereference past end");
15    return (*p)[curr];
16}
17
18StrBlobPtr &StrBlobPtr::incr()
19{
20    check(curr, "increment past end of StrBlobPtr");
21    ++curr;
22    return *this;
23}

StrBlob


声明

 1class StrBlobPtr;
 2
 3class StrBlob
 4{
 5    friend class StrBlobPtr; // StrBlobPtr会访问StrBlob的data
 6
 7public:
 8    // ...
 9    StrBlobPtr begin() { return StrBlobPtr(*this); }
10    StrBlobPtr end() {
11        auto ret = StrBlobPtr(*this, data->size());
12        return ret;
13    }
14};