0

If I understand correctly, value initialization T obj {}; uses the user-define constructor while default initialization T obj; either uses the user-define constructor or leaves obj uninitialized (i.e. undefined).

Since having uninitialized values is in general bad style, should we always prefer value initialization over default initialization? Is there any scenario where default initialization is actually better than value initialization?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
AJL
  • 23
  • 4
  • 3
    For classes, both forms use the default constructor. – Pete Becker Dec 03 '22 at 22:21
  • The best way is to not declare the variable until you have a *real* value to give it. That way you don't have to choose. Uninitialized buffers can occationally be useful, if you are reading large files into a buffer. Then it is kind of a waste to clear it first, and then overwrite it immediately. But that is abou the only use for uniitialized variables. – BoP Dec 03 '22 at 22:22

1 Answers1

2

T obj; either uses the user-define constructor or leaves obj uninitialized (i.e. undefined).

obj in this case is initialised. Moreover all non-static members of class type are also default-initialised and only non-static members of built-in types (pointers, int, char, etc...) are left with indeterminate value. That means that required memory is allocated for those members anyway, but no extra effort was done to set them to any specific value (my personal analogy from C programming language is malloc vs calloc functions).

T obj {}; uses the user-define constructor while default initialization T obj; either uses the user-define constructor or leaves obj uninitialized

If a user defined constructor is provided, both default initialisation and value initialisation ({}) invoke the same constructor and have the same effect (depending on how the constructor is implemented).

If there is no user-defined default constructor (or it's defined with default keyword) and no constructors that take a std::initializer_list parameter then value initialisation ({}) ensures that all non-static members are value-initialised, while default initialisation ensures that the members are default-initialised (for primitives it means their value is indeterminate).

should we always prefer value initialization over default initialization?

Zero-initialisation is an additional computation, and in C++ you don't pay for what you don't use, so in case you don't need some parts of your class to have determinate value, you can use default initialisation (T obj) instead of value initialisation (T obj{}) to buy some computation power.

The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49