6

Is there a difference between the 2 initailizations of an object.

Object obj(constructor_arguments);

or

Object obj = Object(constructor_arguments);

Note that the second initialization is not intended to be a pointer with the new operator. It is intended to be a non heap variable.

In GCC both compile and work fine and I'm wondering if there is actually any difference or if both statements are semantically the same.

kris
  • 161
  • 2
  • 4
  • 1
    The best way to see if there is an actual difference is to check the generated assembly code. The first initialization is better, but the second version is likely optimized to the same thing if you let the compiler do its magic. – Marc Claesen May 28 '13 at 20:24
  • 1
    Possible duplicate of http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization-and-direct-initializati – syam May 28 '13 at 20:25
  • @MarcClaesen which means looking at the generated code isn't the best way. In fact, it's the worst way (in this case), as it can lead to false conclusions. – Luchian Grigore May 28 '13 at 20:25
  • @LuchianGrigore, I see your point but I would say it depends on the question (which is ambiguous in this regard). If the question is '*which is more efficient in theory?*', the answer is most definitely the former. If the question is '*which is more efficient in practice?*' they may well be equivalent after optimization. – Marc Claesen May 28 '13 at 20:27

1 Answers1

11

Yes there is. The first is the syntax for direct initialization, the second is copy initialization.

Theoretically, the second one calls the copy constructor, but this is subject to optimizations.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625