/
eg6.cpp
76 lines (66 loc) · 1.61 KB
/
eg6.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
#include <iostream>
using namespace std;
class integer
{
private:
int * p = nullptr;
public:
integer(int i) : p {new int {i}}
{
cout << "ctor\n";
}
// could also do : integer {i.get()}, which would be better since it repeats less code, but it would also print more than I want
integer(const integer & i) : p {new int {i.get()}}
{
cout << "copy ctor\n";
}
integer(integer && i) : p {i.p}
{
i.p = nullptr;
cout << "move ctor\n";
}
virtual ~integer()
{
delete p;
cout << "dtor\n";
}
integer & operator=(const integer & i)
{
*p = i.get();
cout << "copy=\n";
return *this;
}
integer & operator=(integer && i)
{
// not really more efficient for this class
delete p;
p = i.p;
i.p = nullptr;
cout << "move=\n";
return *this;
}
int get() const
{
return *p;
}
void set(int i)
{
*p = i;
}
};
integer incr(integer i)
{
i.set(i.get() + 1);
return i;
// In some cases, C++ is a bit smarter and can omit copies and call the constructor "outside" the function, like the following.
// Note that this isn't a compiler-specific optimization, the specification actually requires this.
// So don't rely on side effects in your copy constructor! Copy construction from a freshly constructed object should be equivalent to using the freshly constructed object itself.
// return integer {i.get() + 1};
}
int main()
{
integer i {1};
integer j {2};
j = incr(i);
cout << j.get() << "\n";
}