C++11 详解:列表初始化、右值引用与移动语义
一、C++11 的发展历史
C++11 是 C++ 的第二个主要版本,是从 C++98 起最重要的更新。它引入了大量更改,标准化了既有实践,并改进了对 C++ 程序员可用的抽象。在它最终由 ISO 在 2011 年 8 月 12 日采纳前,人们曾使用名称'C++0x'。C++03 与 C++11 期间花了 8 年时间,这是迄今为止最长的版本间隔。从那时起,C++ 有规律地每 3 年更新一次。
C++11 引入列表初始化统一对象构造方式,支持内置及自定义类型。std::initializer_list 使容器支持变长参数初始化。右值引用区分左值与右值,解决临时对象生命周期问题。移动语义通过窃取资源而非拷贝提升深拷贝类性能,优化传值返回场景。编译器优化可合并构造步骤。

C++11 是 C++ 的第二个主要版本,是从 C++98 起最重要的更新。它引入了大量更改,标准化了既有实践,并改进了对 C++ 程序员可用的抽象。在它最终由 ISO 在 2011 年 8 月 12 日采纳前,人们曾使用名称'C++0x'。C++03 与 C++11 期间花了 8 年时间,这是迄今为止最长的版本间隔。从那时起,C++ 有规律地每 3 年更新一次。

C++98 中一般数组和结构体可以用{}进行初始化。
struct Point { int _x; int _y; };
int main() {
int array1[] = { 1, 2, 3, 4, 5 };//先开 5 个整型类型的空间,再将值拷贝进去
int array2[5] = { 0 };
Point p = { 1, 2 };
return 0;
}

#include<iostream>
#include<vector>
using namespace std;
struct Point { int _x; int _y; };
class Date {
public:
Date(int year = 1, int month = 1, int day = 1) :_year(year), _month(month), _day(day) { cout << "Date(int year, int month, int day)" << endl; }
Date(const Date& d) :_year(d._year), _month(d._month), _day(d._day) { cout << "Date(const Date& d)" << endl; }
private:
int _year;
int _month;
int _day;
};
// 一切皆可用列表初始化,且可以不加=
int main() {
// C++98 支持的
int a1[] = { 1, 2, 3, 4, 5 };
int a2[5] = { 0 };
Point p = { 1, 2 };
// C++11 支持的
// 内置类型支持
int x1 = { 2 };
// 自定义类型支持
// 这里本质是用{ 2025, 1, 1}构造一个 Date 临时对象
// 临时对象再去拷贝构造 d1,编译器优化后合二为一变成{ 2025, 1, 1}直接构造初始化 d1
// 运行一下,我们可以验证上面的理论,发现是没调用拷贝构造的
// 本质都是由构造函数支持的隐式类型转换
Date d1 = { 2025, 1, 1 };
// 这里是传了一个参数,只要是传单个参数去初始化的就是单参数的隐式类型转换
Date d11 = 2008;
// 这里 d2 引用的是{ 2024, 7, 25 }构造的临时对象,临时对象具有常性所以要加上 const,不然就涉及权限的放大
const Date& d2 = { 2024, 7, 25 };
// 需要注意的是 C++98 支持单参数时类型转换,也可以不用{}
Date d3 = { 2025 };
Date d4 = 2025;
// 可以省略掉=
Point p1{ 1, 2 };
int x2{ 2 };
Date d6{ 2024, 7, 25 };
const Date& d7{ 2024, 7, 25 };
// 不支持,只有{}初始化,才能省略=
// Date d8 2025;
vector<Date> v;
v.push_back(d1);//有名对象
v.push_back(Date(2025, 1, 1));//匿名对象
// 比起有名对象和匿名对象传参,这里{}更有性价比
v.push_back({ 2025, 1, 1 });
return 0;
}
vector v1 = {1,2,3}; vector v2 = {1,2,3,4,5};(这就是 initializer_list 的主要作用!)auto il = { 10, 20, 30 }; // the type of il is an initializer_list,这个类的本质是底层开一个数组,将数据拷贝过来,std::initializer_list 内部有两个指针分别指向数组的开始和结束(结束位置不是 30,而是 30 的下一个位置)。下面代码助解上面的第四点内容
// STL 中的容器都增加了一个 initializer_list 的构造
vector(initializer_list<value_type> il, const allocator_type& alloc = allocator_type());
list(initializer_list<value_type> il, const allocator_type& alloc = allocator_type());
map(initializer_list<value_type> il, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type());
// ...
template<class T> class vector {
public:
typedef T* iterator;
vector(initializer_list<T> l) { for (auto& e : l) push_back(e) }
private:
iterator _start = nullptr;
iterator _finish = nullptr;
iterator _endofstorage = nullptr;
};
// 另外,容器的赋值也支持 initializer_list 的版本
vector& operator= (initializer_list<value_type> il);
map& operator= (initializer_list<value_type> il);
结合代码场景去理解上面的知识点

#include<iostream>
#include<vector>
#include<string>
#include<map>
using namespace std;
int main() {
std::initializer_list<int> mylist;
mylist = { 10, 20, 30 };
cout << sizeof(mylist) << endl;
// 这里 begin 和 end 返回的值 initializer_list 对象中存的两个指针
// 这两个指针的值跟 i 的地址跟接近,说明数组存在栈上
int i = 0;
cout << mylist.begin() << endl;
cout << mylist.end() << endl;
cout << &i << endl;
// {}列表中可以有任意多个值
// 这两个写法语义上还是有差别的,第一个 v1 是直接构造,
// 第二个 v2 是构造临时对象 + 临时对象拷贝 v2+优化为直接构造
vector<int> v1({ 1,2,3,4,5 });
vector<int> v2 = { 1,2,3,4,5 };
const vector<int>& v3 = { 1,2,3,4,5 };//这里引用的是{ 1,2,3,4,5 }构造的临时对象
// 这里是 pair 对象的{}初始化和 map 的 initializer_list 构造结合到一起用了
// 内层的括号是 pair 类型的隐式类型转换,外层括号是 initializer_list 的列表
map<string, string> dict = { {"sort", "排序"}, {"string", "字符串"} };
//对比上面的代码,这里算是把上面的代码步骤拆解开来如下
pair<string, string> kv1 ("sort", "排序");
pair<string, string> kv2 ("string", "字符串");
map<string, string> m1 = { kv1,kv2 };
// initializer_list 版本的赋值支持
v1 = { 10,20,30,40,50 };
return 0;
}
总结
(1)任意类型(内置类型,自定义类型)都支持列表初始化,自定义类型的列表初始化是借助构造支持的,构造里面有几个参数列表里面就可以有几个参数;
(2)
vector<int> v1({ 1,2,3,4,5 });initializer_list 主要是为 STL 容器所准备的,让容器都支持任意多个类型的参数去初始化。本质上是将列表里面的值传给容器里面 initializer_list 的那个构造函数,用 initializer_list 去构造一个 vector 的一个临时对象,再将这个临时对象拷贝构造给 v1,编译器优化为直接构造。(这个本质应该结合上面的第四点以及第四点附带的代码才能进行深度理解)

C++98 的 C++ 语法中就有引用的语法,而 C++11 中新增了的右值引用语法特性,C++11 之后我们之前学习的引用就叫做左值引用。无论左值引用还是右值引用,都是给对象取别名。
#include<iostream>
using namespace std;
int main() {
// 左值:可以取地址
// 以下的 p、b、c、*p、s、s[0] 就是常见的左值
int* p = new int(0);
int b = 1;
const int c = b;
*p = 10;
string s("111111");
s[0] = 'x';
cout << &c << endl;
// 这里 s[0] 返回值类型是 char,&s[0] 类型是 char*,char* 的指针打印的时候不会去按地址去打印,double*,int*会按地址去打印
// 此时需要去强转(void*)
cout << (void*)&s[0] << endl;
// 右值:不能取地址
double x = 1.1, y = 2.2;
// 以下几个,10、x + y、fmin(x, y)、string("11111") 都是常见的右值
10;
x + y;
fmin(x, y);
string("11111");
//cout << &10 << endl;
//cout << &(x+y) << endl;
//cout << &(fmin(x, y)) << endl;
//cout << &string("11111") << endl;
return 0;
}
Type& r1 = x; Type&& rr1 = y; 第一个语句就是左值引用,左值引用就是给左值取别名,第二个就是右值引用,同样的道理,右值引用就是给右值取别名;template typename remove_reference::type&& move (T&& arg);template <class _Ty> remove_reference_t<_Ty>&& move(_Ty&& _Arg) {
// forward _Arg as movable
return static_cast<remove_reference_t<_Ty>&&>(_Arg);
}
#include<iostream>
using namespace std;
int main() {
// 左值:可以取地址
// 以下的 p、b、c、*p、s、s[0] 就是常见的左值
int* p = new int(0);
int b = 1;
const int c = b;
*p = 10;
string s("111111");
s[0] = 'x';
double x = 1.1, y = 2.2;
// 左值引用给左值取别名
int& r1 = b;
int*& r2 = p;
int& r3 = *p;
string& r4 = s;
char& r5 = s[0];
// 右值引用给右值取别名
int&& rr1 = 10;
double&& rr2 = x + y;
double&& rr3 = fmin(x, y);
string&& rr4 = string("11111");
// 左值引用不能直接引用右值,但是 const 左值引用可以引用右值
const int& rx1 = 10;
const double& rx2 = x + y;
const double& rx3 = fmin(x, y);
const string& rx4 = string("11111");
// 右值引用不能直接引用左值,但是右值引用可以引用 move(左值)
int&& rrx1 = move(b);
int*&& rrx2 = move(p);
int&& rrx3 = move(*p);
string&& rrx4 = move(s);
string&& rrx5 = (string&&)s;//这里的()就是将左值强转为右值的意思
// b、r1、rr1 都是变量表达式,都是左值
cout << &b << endl;
cout << &r1 << endl;
cout << &rr1 << endl;
// 这里要注意的是,rr1 的属性是左值,所以不能再被右值引用绑定,除非 move 一下
int& r6 = r1;
// int&& rrx6 = rr1;
int&& rrx6 = move(rr1);
return 0;
}
右值引用可用于为临时对象延长生命周期;const 的左值引用也能延长临时对象生存期,但这些对象无法被修改。
#include<iostream>
#include<string>
using namespace std;
int main() {
std::string s1 = "Test";
// std::string&& r1 = s1; // 错误:不能绑定到右值
// 这里 s1+s2 运算的结果存到一个临时对象,临时对象和匿名对象的生命周期都只是在当前这一行
// r2 作为临时对象的别名,所以临时对象的生命周期会因为 r2 而被延长,生命周期与 r2 相同
const std::string& r2 = s1 + s1; // OK:到 const 的左值引用延长生存期
// r2 += "Test"; // 错误:不能通过到 const 的引用修改
std::string&& r3 = s1 + s1; // OK:右值引用延长生存期
r3 += "Test"; // OK:能通过到非 const 的引用修改
std::cout << r3 << '\n';
return 0;
}

#include<iostream>
using namespace std;
void f(int& x) {
std::cout << "左值引用重载 f(" << x << ")\n";
}
void f(const int& x) {
std::cout << "到 const 的左值引用重载 f(" << x << ")\n";
}
void f(int&& x) {
std::cout << "右值引用重载 f(" << x << ")\n";
}
int main() {
int i = 1;
const int ci = 2;
f(i); // 调用 f(int&)
f(ci); // 调用 f(const int&)
f(3); // 调用 f(int&&),如果没有 f(int&&) 重载则会调用 f(const int&)
f(std::move(i)); // 调用 f(int&&)
// 注意:右值引用变量在用于表达式时是左值属性
int&& x = 1;
f(x); // 调用 f(int& x)
f(std::move(x)); // 调用 f(int&& x)
return 0;
}

左值引用主要使用场景是在函数中左值引用传参和左值引用传返回值时减少拷贝,提高效率,同时还可以修改实参和修改返回对象的价值。左值引用已经解决大多数场景的拷贝效率问题,但是有些场景不能使用传左值引用返回,如下面的 addStrings 和 generate 函数(对象出了作用域还在才可以用左值引用返回,如果出了作用域对象就销毁了就不能使用左值引用返回),C++98 中的解决方案只能是被迫使用输出型参数解决。
那么 C++11 以后这里可以使用右值引用做返回值解决吗?显然是不可能的,因为这里的本质是返回对象是一个局部对象,函数结束这个对象就析构销毁了,右值引用返回也无法改变对象已经析构销毁的事实。
class Solution {
public:
// 传值返回需要拷贝
string addStrings(string num1, string num2) {
string str;
int end1 = num1.size() - 1, end2 = num2.size() - 1;
// 进位
int next = 0;
while (end1 >= 0 || end2 >= 0) {
int val1 = end1 >= 0 ? num1[end1--] - '0' : 0;
int val2 = end2 >= 0 ? num2[end2--] - '0' : 0;
int ret = val1 + val2 + next;
next = ret / 10;
ret = ret % 10;
str += ('0' + ret);
}
if (next == 1) str += '1';
reverse(str.begin(), str.end());
return str;
}
};
class Solution {
public:
// 这里的传值返回拷贝代价就太大了
vector<vector<int>> generate(int numRows) {
vector<vector<int>> vv(numRows);
for (int i = 0; i < numRows; ++i) {
vv[i].resize(i + 1, 1);
}
for (int i = 2; i < numRows; ++i) {
for (int j = 1; j < i; ++j) {
vv[i][j] = vv[i - 1][j] + vv[i - 1][j - 1];
}
}
return vv;
}
};
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<assert.h>
#include<string.h>
#include<algorithm>
using namespace std;
namespace lrq {
class string {
public:
typedef char* iterator;
typedef const char* const_iterator;
iterator begin() { return _str; }
iterator end() { return _str + _size; }
const_iterator begin() const { return _str; }
const_iterator end() const { return _str + _size; }
string(const char*) :_size(strlen(str)), _capacity(_size) {
cout << "string(char* str)-构造" << endl;
_str = new char[_capacity + 1];
strcpy(_str, str);
}
void swap(string& s) {
::swap(_str, s._str);
::swap(_size, s._size);
::swap(_capacity, s._capacity);
}
string(const string& s) :_str(nullptr) {
cout << "string(const string& s) -- 拷贝构造" << endl;
reserve(s._capacity);
for (auto ch : s) {
push_back(ch);
}
}
// 移动构造。注意:这里的 s 此时是左值属性,延长了临时变量的生命周期,就可以进行 swap 修改,移动资源
string(string&& s) {
cout << "string(string&& s) -- 移动构造" << endl;
swap(s);
}
string& operator=(const string& s) {
cout << "string& operator=(const string& s) -- 拷贝赋值" << endl;
if (this != &s) {
_str[0] = '\0';
_size = 0;
reserve(s._capacity);
for (auto ch : s) {
push_back(ch);
}
}
return *this;
}
// 移动赋值
string& operator=(string&& s) {
cout << "string& operator=(string&& s) -- 移动赋值" << endl;
swap(s);
return *this;
}
~string() {
cout << "~string() -- 析构" << endl;
delete[] _str;
_str = nullptr;
}
char& operator[](size_t pos) {
assert(pos < _size);
return _str[pos];
}
void reserve(size_t n) {
if (n > _capacity) {
char* tmp = new char[n + 1];
if (_str) {
strcpy(tmp, _str);
delete[] _str;
}
_str = tmp;
_capacity = n;
}
}
void push_back(char ch) {
if (_size >= _capacity) {
size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
reserve(newcapacity);
}
_str[_size] = ch;
++_size;
_str[_size] = '\0';
}
string& operator+=(char ch) {
push_back(ch);
return *this;
}
const char* c_str() const { return _str; }
size_t size() const { return _size; }
private:
char* _str = nullptr;
size_t _size = 0;
size_t _capacity = 0;
};
}
int main() {
lrq::string s1("xxxxx");
// 拷贝构造
lrq::string s2 = s1;
// 构造 + 移动构造,优化后直接构造
lrq::string s3 = lrq::string("yyyyy");
// 移动构造,将左值变为右值属性
//lrq::string s4 = move(s1);
cout << "******************************" << endl;
return 0;
}

namespace lrq {
string addStrings(string num1, string num2) {
string str;
int end1 = num1.size() - 1, end2 = num2.size() - 1;
int next = 0;
while (end1 >= 0 || end2 >= 0) {
int val1 = end1 >= 0 ? num1[end1--] - '0' : 0;
int val2 = end2 >= 0 ? num2[end2--] - '0' : 0;
int ret = val1 + val2 + next;
next = ret / 10;
ret = ret % 10;
str += ('0' + ret);
}
if (next == 1) str += '1';
reverse(str.begin(), str.end());
cout << "******************************" << endl;
return str;
}
}
// 场景 1
int main() {
lrq::string ret = lrq::addStrings("11111", "2222");
cout << ret.c_str() << endl;
return 0;
}
// 场景 2
int main() {
lrq::string ret;
ret = lrq::addStrings("11111", "2222");
cout << ret.c_str() << endl;
return 0;
}

图一

图二

图三


图四

图五


微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online