Repository navigation
Expand file tree
/
Copy pathrule_of_three.cpp
More file actions
71 lines (57 loc) · 2.04 KB
/
Copy pathrule_of_three.cpp
File metadata and controls
71 lines (57 loc) · 2.04 KB
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
#include <stdlib.h>
#include <iostream>
class MyMovableClass
{
private:
int _size;
int *_data;
public:
MyMovableClass(size_t size) // constructor
{
_size = size;
_data = new int[_size];
std::cout << "CREATING instance of MyMovableClass at " << this << " allocated with size = " << _size*sizeof(int) << " bytes" << std::endl;
}
MyMovableClass(const MyMovableClass &source) // 2 : copy constructor
{
_size = source._size;
_data = new int[_size];
*_data = *source._data;
std::cout << "COPYING content of instance " << &source << " to instance " << this << std::endl;
}
MyMovableClass &operator=(const MyMovableClass &source) // 3 : copy assignment operator
{
std::cout << "ASSIGNING content of instance " << &source << " to instance " << this << std::endl;
if (this == &source)
return *this;
delete[] _data;
_data = new int[source._size];
*_data = *source._data;
_size = source._size;
return *this;
}
~MyMovableClass() // 1 : destructor
{
std::cout << "DELETING instance of MyMovableClass at " << this << std::endl;
delete[] _data;
}
};
MyMovableClass createObject(int size){
MyMovableClass obj(size); // regular constructor
return obj; // return MyMovableClass object by value
}
int main()
{
MyMovableClass obj1(10); // regular constructor
MyMovableClass obj2(obj1); // copy constructor
obj2 = obj1; // copy assignment operator
// call to copy constructor, (alternate syntax)
MyMovableClass obj3 = obj1;
// Here, we are instantiating obj3 in the same statement; hence the copy assignment operator would not be called.
//MyMovableClass obj4 = createObject(10);
// createObject(10) returns a temporary copy of the object as an rvalue, which is passed to the copy constructor.
//You can try executing the statement below as well
//MyMovableClass obj4(createObject(10));
MyMovableClass obj4 = createObject(10);
return 0;
}