目录
1.列表初始化
{}初始化
C++98中
C++11中
内置置类型和自定义类型
创建对象也适用
std::initializer_list
2.变量类型推导
auto
C++98
C++11
decltype
nullptr
3.范围for循环
4.STL中一些变化
array
1.创建和初始化
2.访问元素
编辑
3.修改操作
4.支持迭代器
forward_list
1.创建和初始化
2.访问元素
3.修改操作
4.支持迭代器
5.右值引用和移动语义
左值引用和右值引用
左值:
右值:
C++11进一步细分:
使用场景
1.函数重载
2.移动语义 (移动构造)
移动构造的触发场景
a. 显式使用 std::move
b.函数返回临时对象
c.接收返回值的构造
d.标准库容器操作
3. 完美转发
4.特殊案例
返回左值引用的函数
5.左值与右值的对比
6.左值引用与右值引用的对比
7.左值引用的短板
用右值引用和移动语义可以解决上述问题:
8.右值引用引用引用左值
1.列表初始化
{}初始化
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中
内置置类型和自定义类型
扩大了用大括号括起的列表(初始化列表)的使用范围,使其可用于所有的内置类型和用户自定义的类型,使用初始化列表时,可添加等号(=),也可不添加
struct Point
{int _x;int _y;
};int main()
{int x1 = 1;int x2{ 2 };int array1[] = { 1, 2,3 ,4, 5 };int array2[]{ 1,2,3,4,5 }; // 可加等号,也可不加Point p{ 1, 2 };// c++11中列表初始化也可以适用于new表达式中int* pa = new int[4] {0};return 0;
}
创建对象也适用
class Date
{
public:Date(int year, int month, int day):_year(year), _month(month), _day(day){cout << "Date(int year, int month, int day)" << endl;}
private:int _year;int _month;int _day;
};int main()
{Date d1(2022, 1, 1); // 旧时用法// C++11支持的列表初始化,这里会调用构造函数初始化Date d2{ 2022, 1, 2 };Date d3 = { 2022, 1, 3 }; // 等号可用可不用return 0;
}
std::initializer_list
int main()
{// the type of il is an initializer_list auto il = { 10, 20, 30 };cout << typeid(il).name() << endl;return 0;
}
std::initializer_list 一般是作为构造函数的参数, C++11 对 STL 中的不少容器就增加std::initializer_list作为参数的构造函数,这样初始化容器对象就更方便了。也可以作为 operator= 的参数,这样就可以用大括号赋值
int main()
{vector<int> v = { 1,2,3,4 };list<int> lt = { 1,2 };// 这里{"sort", "排序"}会先初始化构造一个pair对象map<string, string> dict = { {"sort", "排序"}, {"insert", "插入"} };// 使用大括号对容器赋值v = { 10, 20, 30 };return 0;
}
2.变量类型推导
auto
C++98
在 C++98 中 auto 是一个存储类型的说明符,表明变量是局部自动存储类型,但是局部域中定义局部的变量默认就是自动存储类型,所以auto 就没什么价值了。int main() {auto int x = 10; // C++98: auto 表示 x 是自动存储类型(默认就是 auto,所以多余)int y = 20; // 默认就是 auto,等同于 auto int y = 20;return 0; }
结论:auto 在 C++98 中几乎没用,因为局部变量默认就是 auto。
C++11
C++11 废弃了 auto 的旧用法,并赋予它 自动类型推断 的功能:1.auto 可以让编译器自动推断变量的类型,但必须 显式初始化(即必须赋值)。2.适用于复杂类型、模板、迭代器等场景,减少代码冗余。
int main() {// 基本类型auto x = 10; // x 的类型是 int(编译器自动推断)auto y = 3.14; // y 的类型是 doubleauto name = "Alice"; // name 的类型是 const char*// STL 容器(避免写冗长的类型)std::vector<std::string> names = { "Alice", "Bob", "Charlie" };auto it = names.begin(); // it 的类型是 std::vector<std::string>::iterator// 范围 for 循环(C++11 新增)for (auto& n : names) { // n 的类型自动推断为 std::string&std::cout << n << "\n";}return 0;
}
decltype
关键字 decltype 将变量的类型声明为表达式指定的类型
template<class T1, class T2>
void F(T1 t1, T2 t2)
{decltype(t1 * t2) ret;cout << typeid(ret).name() << endl;
}int main()
{const int x = 1;double y = 2.2;decltype(x * y) ret; // ret的类型是doubledecltype(&x) p; // p的类型是int*cout << typeid(ret).name() << endl;cout << typeid(p).name() << endl;F(1, 'a');return 0;
}
nullptr
由于 C++ 中 NULL 被定义成字面量 0 ,这样就可能回带来一些问题,因为 0 既能指针常量,又能表示整形常量。所以出于清晰和安全的角度考虑,C++11 中新增了 nullptr ,用于表示空指针。
3.范围for循环
范围
for
循环是 C++11 引入的一种简化遍历容器(如数组、vector
、list
等)的语法,它可以自动迭代容器中的所有元素,无需手动管理迭代器或下标。
#include <iostream>int main()
{int arr[] = {1, 2, 3, 4, 5};// 使用范围 for 遍历数组for (auto num : arr) // num 会自动推断为 int{ std::cout << num << " ";}// 输出:1 2 3 4 5return 0;
}
应用范围很广,比起其他的遍历方式,其简单又便捷
4.STL中一些变化
STL新增了一些容器(上图圈出来的)
array
std::array
是 C++11 引入的一个固定大小的顺序容器,它结合了 C 风格数组的性能和标准容器的便利接口。
与普通数组做比较:
1.创建和初始化
int main()
{// 创建并初始化std::array<int, 5> arr1 = { 1, 2, 3, 4, 5 };// 统一初始化 (C++11) -- 列表初始化std::array<int, 3> arr2{7, 8, 9};// 默认初始化 (元素值未定义)std::array<double, 4> arr3;// 全部初始化为0std::array<int, 5> arr4{};return 0;
}
2.访问元素
int main()
{std::array<int, 5> nums = { 10, 20, 30, 40, 50 };// 使用下标访问 (不检查边界)int x = nums[2]; // 30// 使用at()访问 (检查边界)int y = nums.at(3); // 40// nums.at(5) 会抛出 std::out_of_range 异常// 访问首尾元素int first = nums.front(); // 10int last = nums.back(); // 50// 打印出来std::cout << x << " " << y << " " << first << " " << last << std::endl;// 使用迭代器for (auto it = nums.begin(); it != nums.end(); ++it) {std::cout << *it << " ";}return 0;
}
3.修改操作
int main()
{std::array<int, 5> nums{1, 2, 3, 4, 5};// 填充值nums.fill(10); // 所有元素变为10// 交换两个arraystd::array<int, 5> other{5, 4, 3, 2, 1};nums.swap(other); // nums和other内容交换return 0;
}
4.支持迭代器
int main()
{std::array<std::string, 3> colors{"red", "green", "blue"};// 正向迭代for (auto it = colors.begin(); it != colors.end(); ++it) {std::cout << *it << " ";}// 反向迭代for (auto rit = colors.rbegin(); rit != colors.rend(); ++rit) {std::cout << *rit << " ";}// 范围for循环 (C++11)for (const auto& color : colors) {std::cout << color << " ";}return 0;
}
forward_list
std::forward_list
是 C++11 引入的单向链表容器,比std::list
更节省内存,但功能稍有限制。
与 std::list
的比较:
1.创建和初始化
int main()
{// 创建空链表std::forward_list<int> flist1;// 创建并初始化std::forward_list<int> flist2 = { 1, 2, 3, 4, 5 };// 指定大小和默认值std::forward_list<int> flist3(5, 100); // 5个元素,每个都是100return 0;
}
2.访问元素
int main()
{std::forward_list<int> nums = { 10, 20, 30, 40, 50 };// 访问第一个元素int first = nums.front(); // 10// 不能直接访问最后一个元素(需要遍历)// nums.back() 不存在!// 遍历所有元素for (int num : nums) {std::cout << num << " ";}return 0;
}
3.修改操作
int main()
{std::forward_list<int> nums = { 1, 2, 3 };// 在前面插入元素nums.push_front(0); // 现在: 0, 1, 2, 3// 删除第一个元素nums.pop_front(); // 现在: 1, 2, 3// 在特定位置后插入元素auto it = nums.begin();nums.insert_after(it, 99); // 现在: 1, 99, 2, 3// 删除特定位置后的元素nums.erase_after(it); // 现在: 1, 2, 3return 0;
}
4.支持迭代器
int main()
{std::forward_list<int> flist = { 1, 2, 3, 4, 5 };// 获取指向第一个元素的迭代器auto begin_it = flist.begin();// 获取尾后迭代器auto end_it = flist.end();// 传统方式遍历for (auto it = flist.begin(); it != flist.end(); ++it) {std::cout << *it << " ";}// 范围for循环 (推荐)for (const auto& elem : flist) {std::cout << elem << " ";}return 0;
}
5.右值引用和移动语义
传统的C++语法中就有引用的语法,而C++11中新增了的右值引用语法特性
左值引用和右值引用
左值:
左值是指那些有明确内存地址、可以取地址的表达式,通常代表一个持久存在的对象。
特点:
1.可以出现在赋值语句的左侧
2.有持久的状态(超出单个表达式仍然存在)
3.可以取地址(使用&运算符)
int x = 10; // x是左值
int* p = &x; // 可以取x的地址
x = 20; // x可以出现在赋值左侧
右值:
右值是指临时对象或即将被销毁的对象,通常代表一个短暂存在的值。
特点:
1.只能出现在赋值语句的右侧
2.通常是临时对象或字面量
3.不能取地址
int x = 10; // 10是右值
int y = x + 5; // (x+5)是右值
std::string s = "hello"; // "hello"是右值
C++11进一步细分:
使用场景
1.函数重载
2.移动语义 (移动构造)
class MyString {
public:// 移动构造函数MyString(MyString&& other) { // 接受右值引用data = other.data;other.data = nullptr;}private:int* data;
};
移动构造的触发场景
a. 显式使用 std::move
vector<string> func() {vector<string> local;return std::move(local); // 强制移动(但可能阻止RVO)
}
b.函数返回临时对象
vector<string> getTemp() {return vector<string>{"a", "b", "c"}; // 临时对象必然移动
}
c.接收返回值的构造
class String {char* data;
public:// 移动构造函数String(String&& other) noexcept : data(other.data) { // 窃取资源other.data = nullptr;}~String() { delete[] data; }
};String createString() {String temp("hello");return temp; // 返回值优化或移动
}/// ----------------->>
vector<String> strs = createStrings(); // 移动构造或RVO
d.标准库容器操作
vector<string> v1 = {"a", "b"};
vector<string> v2;
v2 = std::move(v1); // 移动赋值
3. 完美转发
template<typename T>
void relay(T&& arg) { // 万能引用process(std::forward<T>(arg)); // 完美转发
}
1. 万能引用(Universal Reference)
T&& arg 中的 && 并不总是表示右值引用。当 T 是模板参数时,T&& 是一个"万能引用",它能绑定到左值或右值:
int x = 10; relay(x); // T被推导为int&,arg绑定到左值 relay(20); // T被推导为int,arg绑定到右值
2. std::forward 的作用
std::forward<T>(arg) 会根据原始参数的值类别决定转发方式:
a.如果原始参数是左值,转发为左值
b.如果原始参数是右值,转发为右值
4.特殊案例
返回左值引用的函数
int& getRef() { static int x; return x; }int main()
{getRef() = 5; // 函数调用是左值return 0;
}
getRef() 返回的是变量x的引用,因此整个函数调用表达式可以当作x本身使用,包括:
1.出现在赋值左侧
2.取地址
3.绑定到非const左值引用
5.左值与右值的对比
6.左值引用与右值引用的对比
7.左值引用的短板
但是当函数返回对象是一个局部变量,出了函数作用域就不存在了,就不能使用左值引用返回,只能传值返回。例如:bit::string to_string(int value) 函数中可以看到,这里只能使用传值返回,传值返回会导致至少1 次拷贝构造 ( 如果是一些旧一点的编译器可能是两次拷贝构造 ) 。
用右值引用和移动语义可以解决上述问题:
在 bit::string 中增加移动构造, 移动构造本质是将参数右值的资源窃取过来,占位已有,那么就不 用做深拷贝了,所以它叫做移动构造,就是窃取别人的资源来构造自己 。
// 移动构造
string(string&& s):_str(nullptr), _size(0), _capacity(0)
{cout << "string(string&& s) -- 移动语义" << endl;swap(s);
}int main()
{bit::string ret2 = bit::to_string(-1234);return 0;
}
8.右值引用引用引用左值
void push_back(value_type&& val);int main()
{list<YC::string> lt;YC::string s1("1111");// 这里调用的是拷贝构造lt.push_back(s1);// 下面调用都是移动构造lt.push_back("2222");lt.push_back(std::move(s1));return 0;
}// 运行结果:
// string(const string& s) -- 深拷贝
// string(string&& s) -- 移动语义
// string(string&& s) -- 移动语义