C++11新特性

一、auto & decltype

1.1 auto

auto:让编译器在编译器就推导出变量的类型,可以通过=右边的类型推导出变量的类型。

1
2
3
4
5
6
auto a = 10; // 10是int型,可以自动推导出a是int

int i = 10;
auto b = i; // b是int型

auto d = 2.0; // d是double型

auto 推导规则:

  • auto 的使用必须马上初始化,否则无法推导出类型
  • auto 在一行定义多个变量时,各个变量的推导不能产生二义性,否则编译失败
  • auto 不能用作函数参数
  • 在类中 auto 不能用作非静态成员变量
  • auto 不能定义数组,可以定义指针
  • auto 无法推导出模板参数
  • 在不声明为引用或指针时,auto 会忽略等号右边的引用类型和 const、volatile 限定
  • 在声明为引用或者指针时,auto 会保留等号右边的引用和 const、volatile 属性
1
2
3
4
5
6
7
8
9
10
int i = 0;
auto *a = &i; // a是int*
auto &b = i; // b是int&
auto c = b; // c是int,忽略了引用

const auto d = i; // d是const int
auto e = d; // e是int

const auto& f = e; // f是const int&
auto &g = f; // g是const int&

1.2 decltype

上面介绍的 auto 用于推导变量类型,而 decltype 则用于推导表达式类型,这里只用于编译器分析表达式的类型,表达式实际不会进行运算。

1
2
3
4
5
6
int func() { return 0; }
decltype(func()) i; // i为int类型

int x = 0;
decltype(x) y; // y是int类型
decltype(x + y) z; // z是int类型

decltype 不会像 auto 一样忽略引用和 const、volatile 属性,decltype 会保留表达式的引用和 const volatile 属性

推导规则:对于 decltype(exp)

  • exp 是表达式,decltype(exp) 和 exp 类型相同
  • exp 是函数调用,decltype(exp) 和函数返回值类型相同
  • 其它情况,若 exp 是左值,decltype(exp) 是 exp 类型的左值引用

1.3 auto 和 decltype 配合使用

auto 和 decltype 一般配合使用在推导函数返回值的类型问题上。

下面看一段代码:

1
2
3
4
template<typename T, typename U>
return_value add(T t, U u) { // t和v类型不确定,无法推导出return_value类型
return t + u;
}

如果这样像下面这样使用 decltype 就会报错, 因为在 decltype(t +u) 推导时,t和u尚未定义,就会编译出错 :

1
2
3
4
template<typename T, typename U>
decltype(t + u) add(T t, U u) { // t和u尚未定义
return t + u;
}

解决办法如下:

C++11 有一个叫做返回类型后置的语法

1
2
3
4
template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u) {
return t + u;
}

返回值后置类型语法就是为了解决函数返回制类型依赖于参数但却难以确定返回值类型的问题。

二、lambda 表达式

三、移动语义

四、基于范围的 for 循环


C++11新特性
http://example.com/2026/04/15/C++11新特性/
作者
Yu xin
发布于
2026年4月15日
许可协议