-
Notifications
You must be signed in to change notification settings - Fork 0
/
13_30.cpp
45 lines (39 loc) · 852 Bytes
/
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
#include <iostream>
#include <string>
using namespace std;
class HasPtr{
public:
friend void swap(HasPtr &, HasPtr &);
HasPtr(const string &s = string()):ps(new string(s)), i(0){}
HasPtr(const HasPtr & hp){
if( hp.ps != ps )
{
ps = new string(*(hp.ps));
}
i = hp.i;
}
HasPtr& operator=(HasPtr rhs)
{
swap(*this, rhs);
return *this;
}
~HasPtr() { delete ps; }
string content() { return *ps; }
private:
string *ps;
int i;
};
inline void swap(HasPtr&lhs, HasPtr&rhs)
{
cout << "using swap method now.\n";
using std::swap;
swap(lhs.ps, rhs.ps);
swap(lhs.i, rhs.i);
}
int main()
{
HasPtr p1("hello world"), p2;
p2 = p1;
cout << p2.content() << endl;
return 0;
}