Narek
Narek

Reputation: 39881

Automatic move constructor

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

Answers (3)

Rehan Haider
Rehan Haider

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

Vaughn Cato
Vaughn Cato

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

c-smile
c-smile

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

Related Questions