Home > Enterprise >  Is there any difference between initializing a class instance with a constructor versus an assignmen
Is there any difference between initializing a class instance with a constructor versus an assignmen

Time:04-20

Is there any difference between declaring and initializing a class instance like this:

MyClass var(param1, param2);

...and this?

MyClass var = MyClass(param1, param2);

I vaguely recall hearing that they're equivalent at some point, but now I'm wondering if the latter case might also call the class's assignment operator, move constructor, or copy constructor rather than just the specific constructor that's explicitly used.

CodePudding user response:

The latter is not an assignment. It's syntax called copy initialisation:

type_name variable_name = other;

The former is direct initialisation:

type_name variable_name(arg-list, ...);

Prior to C 17, there was technically creation of temporary object from the direct initialisation MyClass(param1, param2), and call to copy (or move since C 11) constructor in the latter case. There was no practical difference1 as long as that copy/move was well-formed because that copy was allowed to be optimised away. But it would have been ill-formed if the class wasn't copyable nor movable.

Since C 17, there is no difference1 even for the abstract machine. There's no temporary object and no copy that would need to be optimised. param1, param2 are passed directly to the constructor that initialises var just like what happened previously due to optimisation.

1 Except for the case where the constructor is explicit, in which case copy-initialisation syntax is not allowed as demonstrated by Daniel Langr.

  • Related