大括号初始化没有任何值

Curly brackets initialization without any value

这样写可以吗

typedef unsigned long DWORD;
DWORD nBytesRead = {};

这个表达式后面的变量会是0吗?

是的,这是合法的。标准说 (5.17.9):

A braced-init-list may appear on the right-hand side of an assignment to a scalar, in which case the initializer list shall have at most a single element. The meaning of x={v} , where T is the scalar type of the expression x , is that of x=T(v) except that no narrowing conversion ( 8.5.4 ) is allowed. The meaning of x={} is x=T()

是的,没关系,你保证 nBytesRead 将包含值零。您正在使用一个空的初始化列表对 nBytesRead 进行复制初始化,这对于非 class 类型意味着您正在对其进行零初始化。零初始化的意思正是您所想的意思。


你正在做的事情叫做list-copy-initialization。来自 [dcl.init]:

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

来自[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.

其中:

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.

值初始化,对于非class类型,意味着[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.

零初始化意味着,[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