forked from demon90s/CppStudy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise_13_30.cpp
53 lines (40 loc) · 995 Bytes
/
exercise_13_30.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 练习13.30:为你的类值版本的HasPtr编写swap函数,并测试它。为你的swap函数
// 添加一个打印语句,指出函数什么时候执行。
#include <iostream>
#include <string>
using namespace std;
class HasPtr {
friend void swap(HasPtr&, HasPtr&);
public:
HasPtr(const std::string &s = std::string()) :
ps(new std::string(s)), i(0) {}
HasPtr(const HasPtr &hp) :
ps(new std::string(*hp.ps)), i(hp.i) {}
HasPtr& operator=(const HasPtr &hp) {
auto new_ps = new std::string(*hp.ps);
delete ps;
ps = new_ps;
i = hp.i;
return *this;
}
~HasPtr() { delete ps; }
std::string Value() const { return *ps; }
private:
std::string *ps;
int i;
};
void swap(HasPtr &lhs, HasPtr &rhs)
{
cout << "swap(HasPtr &lhs, HasPtr &rhs)" << endl;
using std::swap;
swap(lhs.ps, rhs.ps);
swap(lhs.i, rhs.i);
}
int main()
{
HasPtr p1("p1"), p2("p2");
swap(p1, p2);
cout << "p1: " << p1.Value() << endl;
cout << "p2: " << p2.Value() << endl;
return 0;
}