Are there any differences between these two lines?

c++

Solution

myClass myVariable = myClass(123);

is copy initialization.

myClass myVariable(123);

is direct initialization.

myClass myVariable;
myVariable = myClass(123);

is default initialization followed by copy (or move) assignment.

Typically, the first two are identical because of copy elision. The relevant rule can be found in [class.copy]/31 (N4140, C++14 draft standard):

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...]:

— when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

Problem

We can create an object in two ways: ``` myClass myObject = myClass(123); //or myClass myObject(123); ``` Are there any differences in background between these two? I want to use the first one but it seems like combining these two lines: ``` myClass myObject; myObject= myClass(123); ``` Does the second one also do the same thing?

Original source