c++ - How smart pointer weak_ptr is bound to shared_ptr in this case? -
here exercise c++ primer 5th edition:
exercise 12.20: write program reads input file line @ time strblob , uses strblobptr print each element in 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
bound data
member of strblob in strblobptr strblob::begin
calling default constructor function.
while in strblobptr strblob::end()
, strblobptr(strblob &a, size_t sz = 0):wptr(a.data), curr(sz) { }
called explicitly , wptr
bound a.data
.
as @tetechhelp answered
strblob::begin doesn't call default constructor (i.e. ctor 0 parameters), calls overloaded constructor default parameter (sz in case defaulted 0); in begin function return strblobptr(*this); same calling return strblobptr(*this, 0);
Comments
Post a Comment