Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between default-initialize and value-initialize? [duplicate]

Possible Duplicate:
What do the following phrases mean in C++: zero-, default- and value-initialization?

I was reading this answer, so I came across the second word : value-initialize. Initially I thought this is same as default-initialize but the context hints me that I'm wrong.

So my question is :

What is the difference between default-initialize and value-initialize?

I would like to understand the difference with some examples.

like image 850
Nawaz Avatar asked Apr 10 '11 08:04

Nawaz


People also ask

What is default initialization in C?

Default member initializer (C++11) [edit] This is the initialization performed when an object is constructed with no initializer.

What is an initialization value?

Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

Are structs default initialized?

Constructors are defined with a function name of this and have no return value. The grammar is the same as for the class Constructor. A struct constructor is called by the name of the struct followed by Parameters. If the ParameterList is empty, the struct instance is default initialized.

Does default constructor zero initialize?

For built-in types it results in zero-initialization.


2 Answers

According to the standard (8.5/4,5):

To default-initialize an object of type T means:
— if T is a non-POD class type the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is an array type, each element is default-initialized;
— otherwise, the object is zero-initialized.


To value-initialize an object of type T means:
— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;96)
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized

like image 104
Karl von Moor Avatar answered Sep 19 '22 17:09

Karl von Moor


"default-initialise" gives it the default value as specified by the standard, which could be garbage.

"value-initialise" initialises it to a specific value - one set in the constructor, for instance, or optimised by the compiler.

like image 38
Ben Stott Avatar answered Sep 23 '22 17:09

Ben Stott