-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy path13.30.cpp
67 lines (58 loc) · 1.32 KB
/
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* 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.
*
* By Faisal Saadatmand
*/
#include <iostream>
#include <string>
class HasPtr {
friend void swap(HasPtr &, HasPtr &);
friend std::ostream& print(std::ostream &, const HasPtr &);
public:
HasPtr(const std::string &s = std::string()) :
ps(new std::string(s)), i(0) {}
~HasPtr() { delete ps; }
HasPtr(const HasPtr& rhs) :
ps(new std::string(*rhs.ps)), i(rhs.i) {}
HasPtr& operator=(HasPtr &);
private:
std::string *ps;
int i;
};
HasPtr&
HasPtr::operator=(HasPtr &rhs)
{
auto newp = new std::string(*rhs.ps);
delete ps;
ps = newp;
i = rhs.i;
return *this;
}
inline void swap(HasPtr &lhs, HasPtr &rhs)
{
using std::swap;
swap(lhs.ps, rhs.ps);
swap(lhs.i, rhs.i);
std::cout << "swap(HasPtr &lhs, HasPtr &rhs)\n";
}
std::ostream& print(std::ostream &os, const HasPtr &p)
{
os << p.ps << ' ' << *p.ps << ' ' << p.i;
return os;
}
int main()
{
HasPtr str1("lhs string");
HasPtr str2("rhs string");
std::cout << "str1: ";
print(std::cout, str1) << '\n';
std::cout << "str2: ";
print(std::cout, str2) << '\n';
swap(str1, str2);
std::cout << "str1: ";
print(std::cout, str1) << '\n';
std::cout << "str2: ";
print(std::cout, str2) << '\n';
return 0;
}