C++11是C++的第二个主要版本,也是自C++98以来最重要的更新。在2011年8月12日最终获得ISO批准之前,它被命名为'C++0x',因为预计它将在2010年之前发布。C++11引入了大量的变化,旨在规范现有实践并改善C++程序员可用的抽象¹。
C++11的一些核心语言特性包括:
- auto和decltype
- 默认和删除函数
- final和override
- 尾随返回类型
- 右值引用
- 移动构造函数和移动赋值运算符
- 范围枚举
- constexpr和文字类型
- 列表初始化
- 委托和继承构造函数
- 大括号或等号初始化器
- nullptr
- long long
- char16_t和char32_t
- 类型别名
- 可变模板
- 泛化(非平凡)联合体
- 泛化POD(平凡类型和标准布局类型)
- Unicode字符串文字
- 用户定义文字
- 属性
- lambda表达式
- noexcept说明符和noexcept运算符
- alignof和alignas
- 多线程内存模型
- 线程局部存储¹
C++11标准库也进行了改进,新增了算法、容器类、原子操作、类型特征、正则表达式、新的智能指针、async()设施以及多线程库³。
C++11引入了许多新特性,下面是一些简单的例子:
- auto和decltype:使用C++11的新特性,您可以在程序中声明任何变量或任何对象,而无需指定其确切类型,只需使用'auto'关键字。这是一些示例代码片段:
auto karl = 62; // karl has type int
double g();
auto s = g(); // s has type double
- 默认和删除函数:默认函数是指编译器自动生成的函数,例如默认构造函数、复制构造函数和赋值运算符。删除函数是指禁止编译器生成默认函数。下面是一个简单的例子:
class Foo {
public:
Foo() = default; // use the default constructor
Foo(const Foo&) = delete; // disable the copy constructor
};
- final和override:final和override关键字用于控制类的继承和虚拟函数的重写。下面是一个简单的例子:
struct Base {
virtual void foo() final; // cannot be overridden in derived classes
};
struct Derived : Base {
void foo() override; // error: cannot override final function
};
- 尾随返回类型:尾随返回类型允许您在参数列表之后指定函数的返回类型。下面是一个简单的例子:
template <typename T, typename U>
auto add(T t, U u) -> decltype(t + u) {
return t + u;
}
- 右值引用:右值引用允许您将临时对象绑定到引用上,从而实现移动语义和完美转发。下面是一个简单的例子:
void foo(std::string&& str) {
std::string s = std::move(str); // move str into s
}
- 移动构造函数和移动赋值运算符:移动构造函数和移动赋值运算符允许您从临时对象中转移资源,而不是复制它们。下面是一个简单的例子:
class Foo {
public:
Foo(Foo&& other) { // move constructor
data = other.data;
other.data = nullptr;
}
Foo& operator=(Foo&& other) { // move assignment operator
if (this != &other) {
delete data;
data = other.data;
other.data = nullptr;
}
return *this;
}
private:
int* data;
};
- lambda表达式
auto f0 = ()[]{return 1;}
auto f1 = (x)[]{return 3*x;}
auto f2 = (x, y)[]{return x+y;}