I see a problem in C++ Primer 5th edition, which goes:
We could have written StrBlobPtr’s deref member as follows, Which version do you think is better and why?
std::string& deref() const
{
return (*check(curr, "dereference past end"))[curr];
}
Here is the simple StrBlobPtr
class:
class StrBlobPtr {
public:
StrBlobPtr(std::shared_ptr<vector<string>> &p, size_t sz = 0):wptr(p), curr(sz) { }
string& deref() const {
auto p = check(curr, "dereference past end"); // !!! Here is the origin version
return (*p)[curr]; // !!! Here is the origin version
}
private:
std::shared_ptr<vector<string>> check(size_t i, const string &msg) const {
auto ret = wptr.lock();
if (!ret) throw std::runtime_error("unbound StrBlobPtr");
if (i >= ret->size()) throw std::out_of_range(msg);
return ret;
}
std::weak_ptr<vector<string>> wptr;
size_t curr;
};
At first, I guess that there are some difference when any exception throw. so I write the test codes as follow:
StrBlobPtr p(make_shared<vector<string>>({"test", "t"}), 2);
cout << p.deref() << endl; // should be out_of_range.
But the result is throw the out_of_range
regardless of which version. I can't see any difference in this two versions. What is the point of this problem?
If there isn't any difference, I prefer the (*check(curr, "dereference past end"))[curr];
, cause there only one line. looks simple.
I am very grateful for anyone can help me...
Aucun commentaire:
Enregistrer un commentaire