Reputation: 39881
If I have the following type:
struct Data
{
std::string str;
std::vector<int> vec;
float f;
private:
Data(){}
};
and I don't define a move constructor, a copy will happen if I do the following?
Data d1;
d1.str = "abc";
d1.vec = {1, 2, 3};
Data d2 = d1;
Upvotes: 0
Views: 105
Reputation: 1061
If a copy constructor is not defined in a class, the compiler itself defines one. If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor.reference tutorialPoint
Upvotes: 1
Reputation: 64308
Assuming you are talking about this line:
Data d2 = d1;
A copy will happen regardless, since d1
isn't an rvalue.
You can use this instead:
Data d2 = std::move(d1);
In which case, a move will happen. Your class will automatically get a move constructor since you haven't defined your own copy constructor, copy assignment operator, move assignment operator, or destructor.
Upvotes: 3
Reputation: 27470
In this case you will have copy construction invocation as two objects d1 and d2 are equally accessible and can be used separately.
Move constructor will be applied only if compiler can guarantee that moveable will not be accessible after the move.
Return value of the function will be move constructed from r:
Data foo() {
Data r = {1,2,3};
return r; // will construct retval using move semantic
}
Data t = foo();
as r cannot be accessed after function return.
Upvotes: 2