只有聚合可以使用初始化列表进行初始化。根据 8.5.1:1,包含用户提供的构造函数可防止结构或类成为聚合:
c++11
8.5.1 聚合 [dcl.init.aggr]
1 - 聚合是一个数组或一个类(第 9 条),没有用户提供的构造函数 [...]
在 C++03 中,
c++03
8.5.1 - 聚合 [dcl.init.aggr]
1 - 聚合是一个数组或一个类(子句类),没有用户声明的构造函数 [...]
聚合不同于 POD ( c++11 9:10);并非所有聚合都是 POD,也不是所有 POD 都是聚合;具有用户提供的析构函数的类可以是聚合但不是 POD,而具有非复制非默认构造函数的类可以是 POD 但不是聚合。
示范:
#include <type_traits>
#include <iostream>
struct non_pod_aggregate { int i, j; ~non_pod_aggregate() {} };
struct non_aggregate_pod { int i, j; non_aggregate_pod(int) {}
non_aggregate_pod() = default; };
int main() {
std::cout << std::is_pod<non_pod_aggregate>::value << '\n'; // false
std::cout << std::is_pod<non_aggregate_pod>::value << '\n'; // true
non_pod_aggregate{0, 0};
// non_aggregate_pod{0, 0}; // does not compile
}
在 C++03 中,所有 POD ( c++03 9:4) 都是聚合,但仍有可能存在不是 POD 的聚合;如上所述,用户提供的析构函数足以使结构失去 POD 的资格。