问题描述
以下是有效现代C ++ (第55页)的报价:
The following is a quote from Effective Modern C++ (page 55):
我尝试过使用std :: array:
I tried this with std::array:
std::array<int, 10> arr{};
,并收到g ++(版本4.8.2)的警告:
and got the warning from g++ (version 4.8.2):
这是当试图从一个空的 std :: initializer_list 构造
std :: array
code>(请参阅的讨论这个警告)。
which is the warning one gets when trying to construct an std::array
from an empty std::initializer_list
(see Why can I initialize a regular array from {}, but not a std::array for a discussion of this warning).
那么,为什么上面的代码不能解释为调用默认构造函数呢?
So, why isn't the above line of code interpreted as calling the default constructor?
推荐答案
这是因为是一个汇总,因此,这在 section 8.5.4
[dcl.init.list] 其中说:
That is because std::array is an aggregate and therefore aggregate initialization is performed this is covered in the draft C++11 standard section 8.5.4
[dcl.init.list] which says:
-
如果初始化器列表没有元素,T是带有默认构造函数的类类型,则对象为
值初始化。
If the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.
否则,如果T是聚合,则执行聚合初始化(8.5.1)。
Otherwise, if T is an aggregate, aggregate initialization is performed (8.5.1).
double ad[] = { 1, 2.0 }; // OK
int ai[] = { 1, 2.0 }; // error: narrowing
struct S2 {
int m1;
double m2, m3;
};
S2 s21 = { 1, 2, 3.0 }; // OK
S2 s22 { 1.0, 2, 3 }; // error: narrowing
S2 s23 { }; // OK: default to 0,0,0
我们可以看到它是不是一个聚合,然后列表继续说:
and we can see if it is not an aggregate then the list goes on and says:
我们可以确认 std :: array
是部分的集合23.3.2.1
[array.overview] :
array<T, N> a = { initializer-list };
其中initializer-list是最多N个元素的逗号分隔列表
类型可转换为T。
where initializer-list is a comma-separated list of up to N elements whose types are convertible to T.
节 8.5.1
引用 8.5.1
汇总 [dcl.init.aggr] 并说:
,我们回到 4
这是我们开始的地方。
and we come full-circle back to section 8.5.4
which is where we started.
这篇关于空括号调用默认构造函数还是调用std :: initializer_list的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!