samedi 25 avril 2015

How smart pointer weak_ptr is bound to shared_ptr in this case?


Here is an exercise from C++ Primer 5th Edition:

Exercise 12.20: Write a program that reads an input file a line at a time into a StrBlob and uses a StrBlobPtr to print each element in that StrBlob.

class StrBlob
{
    friend class StrBlobPtr;
public:
    StrBlob(): data(make_shared<vector<string>>()) { }
    StrBlob(initializer_list<string> il): 
        data(make_shared<vector<string>>(il)) { }
    int 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();

    StrBlobPtr begin();
    StrBlobPtr end();
private:
    shared_ptr<vector<string>> data;
    void check(int i, const string& msg) const;
};

class StrBlobPtr
{
public:
    StrBlobPtr(): curr(0){ }
    StrBlobPtr(StrBlob &a, size_t sz = 0):
            wptr(a.data), curr(sz) { }
    string& deref() const;
    StrBlobPtr& incr();
private:
    shared_ptr<vector<string>> check(size_t i, const string& msg) const;
    weak_ptr<vector<string>> wptr;
    size_t curr;
};

StrBlobPtr StrBlob::begin() 
{
    return StrBlobPtr(*this); 
}

StrBlobPtr StrBlob::end()
{
    return StrBlobPtr(*this, data->size());
}

I don't understand in how smart pointer wptr is bound to the data member of StrBlob in StrBlobPtr StrBlob::begin by calling the default constructor function.

While in StrBlobPtr StrBlob::end(), StrBlobPtr(StrBlob &a, size_t sz = 0):wptr(a.data), curr(sz) { } is called explicitly and wptr is bound to a.data.


Aucun commentaire:

Enregistrer un commentaire