And I faced a concept called move constructor.
What I got from that concept we will use it to increase performance and reduce memory duplication by not copying the objects all over the place.
But I don't know how this work and I'm confused about this. What I understood it's like shallow copy constructor but it nulls out the source pointer of original object and copy the address.
Are objects passed by value? Is that why it needs to use copy constructor?
If I want to not copy object and work with the object itself, can I use & with object?
I know move constructors work with r-value which are temp parameters/objects.
class Move{
private:
int* data;
public:
void set_data_value(int d) {*data = d;}
int get_data_value() {return *data;}
//constructor
Move (int d);
//copy constructor
Move(const Move &source);
//Move constructor
Move(Move &&source) noexcept
//destructor
~Move();
};
Move::Move(int d) {
data = new int;
*data = d;
}
//copy constructor
Move::Move(const Move &source)
//Move constructor
Move::Move(Move &&source) noexcept
: data(source.data) {
source.data = nullptr;
}
Move::~Move {
delete data;
}
void display_move(Move s) { //this will use copy constructor to copy object to work with copied object
cout << s.get_data_value << endl;
}
void display_move(Move &s) { //can i use this to work with the actual object???
cout << s.get_data_value << endl;
}
int main() {
vector<Move> vec;
Move object1{10}; //l-value reference
display_move(object1);
vec.push_back(Move{10}); //r-value reference so it will use move constructor
vec.push_back(std::move(object1)); //casting l-value to r-value so it will use move constructor instead of copy constructor