//Exercises Section 13.3
//Exercise 13.29: Explain why the calls to swap inside swap(HasPtr&,
//HasPtr&) do not cause a recursion loop.
//For the swap inside function feed the library swap.
//Exercise 13.30: Write and test a swap function for your valuelike version of
//HasPtr.Give your swap a print statement that notes when it is executed.
/*class HasPtr {
public:
friend void swap(HasPtr &, HasPtr &);
HasPtr(const string &s = string()) : ps(new string(s)), i(0) { }
HasPtr(const HasPtr &hp) : ps(new string(*hp.ps)), i(hp.i) { }
HasPtr &operator=(HasPtr &hp) {
swap(*this, hp);
return *this;
}
string *ps;
int i;
};
inline void swap(HasPtr &lhs, HasPtr &rhs) {
using std::swap;
swap(lhs.ps, rhs.ps);
swap(lhs.i, rhs.i);
cout << "swap(HasPtr &lhs, HasPtr &rhs)\n";
}
int main() {
HasPtr h("hello "), p("world!");
cout << *h.ps << *p.ps << endl;
swap(h, p);
cout << *h.ps << *p.ps << endl;
return 0;
}*/
//Exercise 13.31: Give your class a < operator and define a vector of
//HasPtrs.Give that vector some elements and then sort the vector.
//Note when swap is called.
/*class HasPtr {
friend void swap(HasPtr &, HasPtr &);
public:
HasPtr(const string &s = string()) : ps(new string(s)), i(0) { }
HasPtr(const HasPtr &hp) : ps(new string(*hp.ps)), i(hp.i) { }
HasPtr &operator=(HasPtr &hp) {
swap(*this, hp);
return *this;
}
void show() const { cout << *ps << endl; }
bool operator<(const HasPtr &hp) const {
return *ps < *hp.ps;
}
string *ps;
int i;
};
inline void swap(HasPtr &lhs, HasPtr &rhs) {
using std::swap;
swap(lhs.ps, rhs.ps);
swap(lhs.i, rhs.i);
cout << "call swap(HasPtr &lhs, HasPtr &rhs)\n";
}
int main() {
HasPtr a("b"), b("c"), c("a");
vector<HasPtr> vec{ a, b, c };
sort(vec.begin(), vec.end());
for (auto const &elem : vec) elem.show();
return 0;
}*/
//Exercise 13.32: Would the pointerlike version of HasPtr benefit from
//defining a swap function ? If so, what is the benefit ? If not, why not?
//No, it needn't to avoid memory allcoation.
13.3. Swap
最新推荐文章于 2024-08-25 06:11:42 发布