Copy and Move Constructors
In the life of the C++ programmer, there are 2 major interesting constructor strategies. One of them is for copping an object and the other for moving data.
The copy constructor is basic structure which receives a reference of an object. The parameter object must be constant because in the copping operation we can’t modify the values of the object. The structure of the method is:
1 |
MyClass(const MyClass & ref); |
The other method is the move constructor that receives reference of the reference object. The structure is;
1 |
MyClass(MyClass && ref); |
this method runs when a method needs to create a copy of data of existing class
In flowing code, you may find an example code
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 |
#include <iostream> class MyClass { private: int *p_int; public: //Constructor MyClass(){ std::cout << "MyClass()" << std::endl; p_int = new int; *p_int = 0; } //Set value on constructor MyClass(int x){ std::cout << "MyClass(" << x << ")" << std::endl; p_int = new int; *p_int = x; } int getValue() const{ return *p_int; } void setValue(int x){ *p_int = x; } //Copy Constructor MyClass(const MyClass & ref){ std::cout << "MyClass(const MyClass & ref)" << std::endl; p_int = new int; *p_int = ref.getValue(); } //Move constructor MyClass(MyClass && ref){ std::cout << "MyClass(MyClass && ref)" << std::endl; p_int = ref.p_int; //after moveing value you have //to set referance pointer as null ref.p_int = nullptr; } void getStatus(){ std::cout << "Value = " << this->getValue() << std::endl; } ~MyClass(){ std::cout << "~MyClass()" << std::endl; delete p_int; } }; MyClass adder(const MyClass &a, const MyClass &b){ MyClass temp; temp.setValue(a.getValue() + b.getValue()); return temp; } int main(){ MyClass x{5}, y{2}; x.setValue(adder(x,y).getValue()); } |
The move constructor has to set pointers to nullptr because if old object destroys its destroy method may delete existing pointer and we can not reach the values on newly created or moved one.
To force a method to run this move controller: you have to include <memory> header file and std::move is the method to call this constructor.