Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguity between default-initialization and value-initialization

I found many articles explaining the difference between "default-initialization and value-initialization" but in fact I didn't understand clearly.

Here's an example:

class A{
   public:
      int x;
};


int main(){
    A a;// default initialization so x has undefined value.
    A b = A(); // value initialization so x is a scalar thus it is value initialized to 0

}

Above it is OK as I guess but here:

int value = 4; // is this considered a value-initialization?

Please help me understand the major differences between the two forms of initializations.

like image 341
Rami Yen Avatar asked Jun 27 '19 00:06

Rami Yen


People also ask

What is an initialization value?

In computer programming, initialization (or initialisation) is the assignment of an initial value for a data object or variable. The manner in which initialization is performed depends on the programming language, as well as the type, storage class, etc., of an object to be initialized.

What is the default initialization value of INT?

For variables in method, we have to initialize them explicitly. So remember these rules: Integer numbers have default value: 0.

Does C++ initialize variables to zero?

Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is given a memory address to use to store data, the default value of that variable is whatever (garbage) value happens to already be in that memory address!


1 Answers

A a; is default initialization, as the effect the default constructor of A is used for initialization. Since the implicitly-generated default constructor of A does nothing, a.x has indeterminate value.

A() is value initialization,

if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;

Note the difference with default initialization, A has an implicitly-defined default constructor, and the object is zero-initialized; so the data memeber x of the temporary object A() will be initialized to 0.

A b = A(); is copy initialization, in concept b is initialized from the temporary object A(), so b.x will be initialized to 0 too. Note that because of copy elision, since C++17 b is guaranteed to be value-initialized directly; the copy/move construction is omitted.

int value = 4; is copy initialization too. value will be initialized to 4.

like image 101
songyuanyao Avatar answered Sep 28 '22 18:09

songyuanyao