List Initialization(列表初始化)
1. Before C++11 (C++11标准之前的初始化方法)
int x = 0;
int y(2);
char c('a');
int arr[] = { 1,2,3 };
char s[] = "Hello";
C++11 also support the old ways (C++11标准仍然支持旧的初始化方法)
2. List Initialization (列表初始化)
2.1. List initialization is a new feature for C++11 (列表初始化是C++11的一个新特性)
2.2. List: braced-init-list (“列表”是用花括号括起来的一(些)值)
2.3. 列表初始化的两个分类
- Direct list initialization (直接列表初始化)
- Copy list initialization (拷贝列表初始化)
//直接列表初始化)
/* Variable initialization */
int x{}; // x is 0;
int y{ 1 }; // y is 1;
/* Array initialization */
int array1[]{ 1,2,3 };
char s1[ 3 ] { 'o', 'k' };
char s3[]{ "Hello" };
//拷贝列表初始化
/* Variable initialization */
int z = { 2 };
/* Array initialization */
int array2[] = { 4,5,6 };
char s2[] = { 'y','e','s' };
char s4[] = { "World" };
char s5[] = "Aloha"; // Omit curly braces (省略花括号)
3. When do we use list initialization (何时使用列表初始化)
3.1. List initialization is also called “unified initialization” (列表初始化也被称为“统一初始化方法”)
Variables and arrays are initialized in the same form (变量和数组用同样的形式初始化)
3.2. There are still some argues about when to use list-init (目前对于何时使用列表初始化仍然有一些争论)
3.3. A point of view(一种观点)
Prefer {} initialization over alternatives unless you have a strong reason not to(尽量使用列表初始化,除非你有个很好的不用它的理由)
Why: List initialization does not allow narrowing(原因:列表初始化不允许“窄化”,即不允许丢失数据精度的隐式类型转换)