Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ optimise construction-and-copy into a copy constructor?

Tags:

c++

Does a C++ compiler automatically convert:

MyObject object2 = object1;

into

MyObject object2( object1 );

?

Or does it treat it like:

MyObject object2;
object2 = object1;

?

like image 471
PP. Avatar asked Jan 22 '26 01:01

PP.


1 Answers

Yes, it's the first one. It's not an "optimisation"; they are two different syntaxes for invoking the copy constructor.

If you want to prove it, try defining a private assignment operator for MyObject. The code should still compile, which proves it can't be equivalent to the second mechanism.

like image 159
Oliver Charlesworth Avatar answered Jan 23 '26 14:01

Oliver Charlesworth