forked from Mooophy/Cpp-Primer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex13.29.30.31.32.cpp
101 lines (83 loc) · 2.43 KB
/
ex13.29.30.31.32.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 03 JAN 2014
* @remark
***************************************************************************/
//!
//! Exercise 13.29:
//! Explain why the calls to swap inside swap(HasPtr&, HasPtr&) do not cause a recursion loop.
// Because the parameters of the two swap functions have different types.
//!
//! 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.
//!
//! 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.
//!
//! 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?
// Essentially, the specific avoiding memory allocation is the reason why it improve
// the performance. As for the pointerlike version, no dynamic memory allocation anyway.
// Thus a specific version for it will not improve the performance.
//!
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
//! revised for ex13.31
class HasPtr
{
friend void swap(HasPtr&, HasPtr&);
friend bool operator <(const HasPtr& lhs, const HasPtr& rhs);
public:
//! default constructor.
HasPtr(const std::string &s = std::string()):
ps(new std::string(s)), i(0) { }
//! copy constructor.
HasPtr(const HasPtr& hp) : ps(new std::string(*hp.ps)), i(hp.i) { }
HasPtr&
operator = (HasPtr rhs);
//! ^^ no const here
//! destructor.
~HasPtr()
{
delete ps;
}
private:
std::string *ps;
int i;
};
//! specific swap.
inline void
swap(HasPtr &lhs, HasPtr &rhs)
{
using std::swap;
swap(lhs.ps, rhs.ps); // swap the pointers, not the string data
swap(lhs.i, rhs.i); // swap the int members
std::cout <<"swapping!\n";
}
//! operator = using specific swap
HasPtr&
HasPtr::operator = (HasPtr rhs)
{
swap(*this,rhs);
return *this;
}
//! operator < overloading
inline bool
operator <(const HasPtr& lhs, const HasPtr& rhs)
{
std::cout << "<ing\n";
return *lhs.ps < *rhs.ps;
}
int main()
{
HasPtr h1("dd"), h2("bb"), h3("cc");
std::vector<HasPtr> v = {h1, h2, h3};
std::sort(v.begin(), v.end());
return 0;
}