Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly brackets initialization without any value

Is it ok to write something like this

typedef unsigned long DWORD;
DWORD nBytesRead = {};

Will this variable contains 0 after this expression?

like image 509
FrozenHeart Avatar asked Sep 18 '15 09:09

FrozenHeart


1 Answers

Yes it's okay and you are guaranteed that nBytesRead will contain the value zero. You are copy-initializing nBytesRead with an empty initializer list, which for a non-class type means that you are zero-initializing it. Zero-initialization means precisely what you think it means.


What you are doing is called list-copy-initialization. From [dcl.init]:

The initialization that occurs in the = form of a brace-or-equal-initializer or [...] is called copy-initialization.

From [dcl.init.list]:

List-initialization is initialization of an object or reference from a braced-init-list. Such an initializer is called an initializer list, and the comma-separated initializer-clauses of the list are called the elements of the initializer list. An initializer list may be empty. List-initialization can occur in direct-initialization or copy-initialization contexts; list-initialization in a direct-initialization context is called direct-list-initialization and list-initialization in a copy-initialization context is called copy-list-initialization.

Where:

List-initialization of an object or reference of type T is defined as follows:
— If T is a class type and [...]
— Otherwise, if T is a character array and [...]
— Otherwise, if T is an aggregate, [...]
— Otherwise, if the initializer list has no elements and T is a class type [...]
— Otherwise, if T is a specialization of std::initializer_list, [...]
— Otherwise, if T is a class type, [...]
— Otherwise, if the initializer list has a single element [...]
— Otherwise, if T is a reference type, [...]
— Otherwise, if the initializer list has no elements, the object is value-initialized.

Value-initialization, for a non-class type, means [dcl.init]:

To value-initialize an object of type T means:
— if T is a (possibly cv-qualified) class type with either no default constructor [...]
— if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor [...]
— if T is an array type, [...]
otherwise, the object is zero-initialized.

Zero-initialization means, [dcl.init]:

To zero-initialize an object or reference of type T means:
— if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T

like image 124
Barry Avatar answered Sep 29 '22 11:09

Barry