如何使用列表初始化对聚合类型进行值初始化
How to value-initialize aggregate types with list-initialization
如何使用列表初始化语法对 C++14 中的聚合类型进行值初始化?
Aggregate_t {};
这被视为聚合初始化,它会为 Aggregate_t
的未初始化成员产生错误或警告。
这可能吗?
编辑:示例
struct Aggregate_t {
int x;
};
int main (int, char**)
{
Aggregate_t {};
return 0;
}
使用 g++-4.9.2 编译:
main.c++: In function ‘int main(int, char**)’:
main.c++:7:16: warning: missing initializer for member ‘Aggregate_t::x’ [-Wmissing-field-initializers]
Aggregate_t {};
^
[dcl.init.aggr]:
7 - If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized [C++14: from its brace-or-equal-initializer or, if there is no brace-or-equal-initializer,] from an empty initializer list (8.5.4).
所以 g++ 对它的警告过于热心了;我不知道在警告有效的情况下保留它的同时避免它的方法,当然除了使用带有预期复制省略的复制初始化:
Aggregate_t a = Aggregate_t();
如何使用列表初始化语法对 C++14 中的聚合类型进行值初始化?
Aggregate_t {};
这被视为聚合初始化,它会为 Aggregate_t
的未初始化成员产生错误或警告。
这可能吗?
编辑:示例
struct Aggregate_t {
int x;
};
int main (int, char**)
{
Aggregate_t {};
return 0;
}
使用 g++-4.9.2 编译:
main.c++: In function ‘int main(int, char**)’:
main.c++:7:16: warning: missing initializer for member ‘Aggregate_t::x’ [-Wmissing-field-initializers]
Aggregate_t {};
^
[dcl.init.aggr]:
7 - If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized [C++14: from its brace-or-equal-initializer or, if there is no brace-or-equal-initializer,] from an empty initializer list (8.5.4).
所以 g++ 对它的警告过于热心了;我不知道在警告有效的情况下保留它的同时避免它的方法,当然除了使用带有预期复制省略的复制初始化:
Aggregate_t a = Aggregate_t();