What is the difference between & ldquo; Thing; & Rdquo; And & ldquo; Thing thing = Thing (); & Rdquo ;, and when should I use one over the other?

advertisements

I don't understand the difference between the two following statements:

Thing thing;

Thing thing = Thing();

Both create a Thing object and put it in the variable thing, right? If so, two questions:

1- What are the technical differences between the two?

2- When should I use one over the other?

Please note:

A- I am not using C++ 11.

B- New to C++, please use newbie-friendly words.


Thing thing;

is default-initialization. If Thing is a class type, it calls the default constructor of Thing, and that's it.

Thing thing = Thing();

value-initializes a temporary Thing and then copies/moves that temporary into thing. In practice compilers will elide the copy/move, making it effectively a value-initialization, but this still requires a copy/move constructor to be available. The = Thing(); syntax is needed to get value-initialization semantics because Thing thing(); is the vexing parse.*

The difference between value-initialization and default-initialization is that in some cases (the exact cases depend on the version of the standard, but a non-union class type with no user-provided constructors, and non-class non-array types, along with arrays of these types qualify in all versions), value-initialization will zero-initialize first before calling the default constructor.

Using the second version is helpful if Thing can be a non-class (e.g., in a template) or is a class type that would get the zero-initialization treatment (e.g., a POD class) and you want it to have well-defined values.

*Thing thing{}; is subtly different in initialization semantics from plain value-initialization in C++14.