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.

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. Commented May 28, 2013 at 20:24
  • 1
    Possible duplicate of stackoverflow.com/questions/1051379/… Commented May 28, 2013 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. Commented May 28, 2013 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. Commented May 28, 2013 at 20:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.