C++11 发展历史
C++11 是 C++ 标准自 C++98 以来最重要的更新,于 2011 年 8 月正式采纳。在此之前它被称为 C++0x,预计 2010 年发布。从 C++03 到 C++11 间隔了 8 年,此后 C++ 更新周期稳定为每 3 年一次。
列表初始化
C++98 传统的 {} 初始化
在 C++98 中,数组和结构体可以使用 {} 进行初始化,但功能有限。
struct Point { int _x; int _y; };
int main() {
int array1[] = { 1, 2, 3, 4, 5 }; // 先分配空间再拷贝
int array2[5] = { 0 };
Point p = { 1, 2 };
return 0;
}
C++11 中的 {} 列表初始化
C++11 试图统一初始化方式,实现'一切对象皆可用{}初始化'。
- 内置类型与自定义类型:都支持列表初始化。自定义类型本质是通过构造函数进行隐式类型转换,中间可能产生临时对象,编译器优化后通常变为直接构造。
- 省略等号:
{}初始化过程中可以省略=。 - 容器便利:在容器
push_back或insert多参数构造的对象时,{}非常便捷。
#include<iostream>
#include<vector>
using namespace std;
struct Point { int _x; int _y; };
class Date {
public:
( year = , month = , day = ) :_year(year), _month(month), _day(day) {
cout << << endl;
}
( Date& d) :_year(d._year), _month(d._month), _day(d._day) {
cout << << endl;
}
:
_year; _month; _day;
};
{
a1[] = { , , , , };
Point p = { , };
x1 = { };
Date d1 = { , , };
Date d11 = ;
Date& d2 = { , , };
Point p1{ , };
x2{ };
Date d6{ , , };
vector<Date> v;
v.({ , , });
;
}


