目录
[一. 列表初始化{}](#一. 列表初始化{})
[1.1 C++98 中传统的{}](#1.1 C++98 中传统的{})
[1.2 C++11 中的{}](#1.2 C++11 中的{})
[1.3 C++11 中的std::initializer_list](#1.3 C++11 中的std::initializer_list)
[二. 右值引用和移动语义](#二. 右值引用和移动语义)
[2.1 左值和右值](#2.1 左值和右值)
[2.2 左值引用和右值引用](#2.2 左值引用和右值引用)
[2.3 延长生命周期](#2.3 延长生命周期)
[2.4 左值和右值的参数匹配](#2.4 左值和右值的参数匹配)
[2.5 右值引用和移动语义的使用场景](#2.5 右值引用和移动语义的使用场景)
[2.5.1 左值引用主要使用场回顾](#2.5.1 左值引用主要使用场回顾)
[2.5.2 移动构造和移动赋值](#2.5.2 移动构造和移动赋值)
[2.5.2.1 右值对象构造,只有拷贝构造,没有移动构造的场景](#2.5.2.1 右值对象构造,只有拷贝构造,没有移动构造的场景)
[2.5.2.2 右值对象构造,有拷⻉构造,也有移动构造的场景](#2.5.2.2 右值对象构造,有拷⻉构造,也有移动构造的场景)
[2.5.2.3 右值对象赋值,只有拷⻉构造和拷⻉赋值,没有移动构造和移动赋值的场景](#2.5.2.3 右值对象赋值,只有拷⻉构造和拷⻉赋值,没有移动构造和移动赋值的场景)
[2.5.2.4 右值对象赋值,既有拷⻉构造和拷⻉赋值,也有移动构造和移动赋值的场景](#2.5.2.4 右值对象赋值,既有拷⻉构造和拷⻉赋值,也有移动构造和移动赋值的场景)
[2.6 右值引用和移动语义在传参中的提效](#2.6 右值引用和移动语义在传参中的提效)
一. 列表初始化{}
1.1 C++98 中传统的{}
cpp
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
struct Point
{
int _a;
int _b;
};
int main()
{
Point P = { 1,2 };
int array1[] = { 1,2,3,4,5 };
int array[5] = { 0 };
}
1.2 C++11 中的{}
- C++11以后,想统一初始化方式:试图实现一切对象皆可用{}初始化,{}初始化也叫列表初始化;
- 内置类型和自定义类型都支持,自定义类型本质是类型转换,中间会产生临时对象,最后优化了以后变成直接构造;
- {}初始化的过程中,可以省略掉=;
- C++11列表初始化的本意是想实现一个大统一的初始化方式,其次在有些场景下列表初始化会带来不少便利,如容器push / inset多参数构造的对象时,{}初始化会很方便。
cpp
#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};
// 这⾥d2引⽤的是{ 2024, 7, 25 }构造的临时对象
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;
}
1.3 C++11 中的std::initializer_list
- 上面的初始化已经很方便,但是对象是容器初始化还是不太方便,比如一个vector对象,我想用N个值去构造初始化,那么我们得实现多个构造函数才能支持,vector<int> v1= {1,2,3}; vector<int> v2 = {1,2,3,4,5};
- C++库中提出std::initializer_list这个类,auto il = { 10, 20, 30 }; // the type of il is an initializer_list ,这个类的本质是底层开⼀个数组,将数据拷贝过来,std::initializer_list内部有两个指针分别指向数组的开始和结束。
- std::initializer_list支持迭代器遍历
- 容器支持一个std::initializer_list的构造函数,也就支持任意多个值构成的{x1,x2,x3......}进行初始化。STL中的容器支持任意多个值构成的{x1,x2,x3......}进行初始化,就是通过std::initializer_list的构造函数支持的。
cpp
int main()
{
vector<int> v1 = { 1,2,3,4 };
vector<int> v2 = { 1,2,3,4,5,6,7,7 };
// 里面的括号是pair列表初始化,外面的是initialize_list
map<string, string> dict = { {"sort","排序"},{"string","字符串"} };
v1 = { 10,20,30 };
auto il = { 10,20,30 };
cout << typeid(il).name() << endl;
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;
return 0;
}
二. 右值引用和移动语义
C++98 中左值引用(Type& )无法绑定右值,大量临时对象的拷贝导致性能浪费。C++11 新增右值引用(Type&&) 和移动语义,通过 "窃取" 右值对象的资源,替代拷贝操作,大幅提升效率。
2.1 左值和右值
- 左值 :是⼀个表示数据的表达式(如变量名或解引用的指针),⼀般是有持久状态,存储在内存中,我们可以获取它的地址,左值可以出现赋值符号的左边,也可以出现在赋值符号右边。定义时const修饰符后的左值,不能给他赋值,但是可以取它的地址。
- 右值 :右值也是⼀个表示数据的表达式,要么是字面值常量、要么是表达式求值过程中创建的临时对象等,右值可以出现在赋值符号的右边,但是不能出现出现在赋值符号的左边,右值不能取地址。
- 值得⼀提的是,左值的英文简写为lvalue,右值的英文简写为rvalue。传统认为它们分别是left value、right value 的缩写。现代C++中,lvalue被解释为loactorvalue的缩写,可意为存储在内存中、有明确存储地址可以取地址的对象,而rvalue被解释为readvalue,指的是那些可以提供数据值,但是不可以寻址,例如:临时变量,字面量常量,存储于寄存器中的变量等,也就是说左值和右值的核心区别就是能否取地址。
cpp
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("11111111111111");
s[0] = 'x';
cout << &p << endl;
cout << &b << endl;
cout << &c << endl;
cout << &(*p) << endl;
cout << &s << endl;
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;
}
2.2 左值引用和右值引用
Type& r1 = x; Type&& rr1 = y;第一个语句就是左值引用,左值引用就是给左值取别名,第二个就是右值引用,同样的道理,右值引用就是给右值取别名。- 左值引用不能直接引用右值,但是const左值引用可以引用右值
- 右值引用不能直接引用左值,但是右值引用可以引用move(左值)
template <class T> typename remove_reference<T>::type&& move (T&& arg)- move是库里面的一个函数模板,本质内部是进行强制类型转换,当然他还涉及一些引用折叠的知识,这个我们后面会细讲。
- 需要注意的是变量表达式都是左值属性,也就意味着一个右值被右值引用绑定后,右值引用变量变量表达式的属性是左值
- 语法层面看,左值引用和右值引用都是取别名,不开空间。从汇编底层的角度看下面代码中r1和rr1汇编层实现,底层都是用指针实现的,没什么区别。底层汇编等实现和上层语法表达的意义有时是背离的,所以不要然到一起去理解,互相佐证,这样反而是陷入迷途。
cpp
int main()
{
int* p = new int(0);
int b = 1;
const int c = b;
*p = 10;
string s("11111111111111");
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;
}
2.3 延长生命周期
右值引用可用于为临时对象延长生命周期,const的左值引用也能延长临时对象生存期,但这些对象无法被修改。(不能改变临时对象的存储位置,也就是说我们无法跨栈帧延长生命周期)
cpp
class A
{
public:
A()
{
cout << "A()" << endl;
}
~A()
{
cout << "~A()" << endl;
}
};
int main()
{
A aa1;
// 延长匿名对象的生命周期
const A& ref1 = A();// const左值引用,但是这样就不能修改了
A&& ref2 = A();// 右值引用
cout << "main end()" << endl;
return 0;
}
2.4 左值和右值的参数匹配
- C++98中,我们实现一个const左值引用作为参数的函数,那么实参传递左值和右值都可以匹配
- C++11之后,分别重载左值引用,const左值引用,右值引用作为形参的f函数,那么实参是左值会匹配f(左值引用),实参是const左值会匹配(const左值引用),实参是右值会匹配f(右值引用)。
- 右值引用变量在用于表示式时属性是左值,这个我们后面还会讲到的,到时候大家就会对它有更直观的认知了。
cpp
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;
}
2.5 右值引用和移动语义的使用场景
2.5.1 左值引用主要使用场回顾
左值引用主要使用场景:**函数中左值引用传参和左值引用传返回值时减少拷贝,同时还可以修改实参和修改返回对象的价值。**左值引用已经解决大多数场景的拷贝效率问题,但是有些场景不能使用传左值引用返回:如addStrings和generate函数,C++98中的解决方案只能是被迫使用输出型参数解决。C++11以后这里可以使用右值引用作为返回值来解决吗?显然这是不可能的,因为这里的本质是返回对象是一个局部对象,函数结束这个对象就析构销毁了,右值引用返回也无法概念对象已经析构销毁的事实。
cpp
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 << &str << endl;
return str;
}
2.5.2 移动构造和移动赋值
- 移动构造函数是一种构造函数,类似拷贝构造函数,移动构造函数要求第一个参数是该类类型的引用,但是不同的是要求这个参数是右值引用,如果还有其他参数,额外的参数必须有缺省值。
- 移动赋值是一个赋值运算符重载,他跟拷贝赋值构成函数重载,类似拷贝赋值函数,移动赋值函数要求第一个参数是该类类型的引用,但是不同的是要求这个参数是右值引用。
- 对于像string/vector这样的深拷贝的类或者深拷贝的成员变量的类,移动构造和移动赋值才有意义,因为移动构造和移动赋值的第一个参数都是右值引用的类型,**他的本质是要"窃取"引用的右值对象的资源,而不是像拷贝构造函数和拷贝赋值那样去拷贝资源,提高效率。**下面的Lotso::string样例实现了移动构造和移动赋值,我们需要结合场景去理解。
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<assert.h>
#include<string.h>
#include<algorithm>
using namespace std;
namespace Lotso
{
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* str = "")
:_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)
{
cout << "string(const string& s) -- 拷贝构造" << endl;
reserve(s._capacity);
for (auto ch : s)
{
push_back(ch);
}
}
// 移动构造
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;
};
// 传值返回需要拷贝
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 << &str << endl;
return str;
}
}
int main
{
bit::string s1("xxxxx");
// 拷⻉构造
bit::string s2 = s1;
// 构造+移动构造,优化后直接构造
bit::string s3 = bit::string("yyyyy");
// 移动构造
bit::string s4 = move(s1);
cout << "******************************" << endl;
return 0;
}
2.5.2.1 右值对象构造,只有拷贝构造,没有移动构造的场景
- 下图1中展现了 vs2019 debug 环境下编译器对拷贝的优化,左边为不优化的情况下,两次拷贝构造,右边为编译器优化的场景下连续步骤中的拷贝合二为一变为一次拷贝构造。
- 需要注意的是在 vs2019的release和 vs2022的debug和release,下面代码优化十分恐怖,会直接将strd对象的构造,str拷贝构造临时对象,临时对象拷贝构造ret对象,合三为一,变为直接构造,要理解这个优化要结合局部对象生命周期和栈帧的角度理解,如图三。
- linux下可以将下面代码拷贝到test.cpp文件,编译时用 g++ test.cpp -fno-elide-constructors 的方式关闭构造优化,运行结果可以看到图1左边没有优化的两次拷贝。
图一:

2.5.2.2 右值对象构造,有拷⻉构造,也有移动构造的场景
- 图2展示了vs2019 debug环境下编译器对拷⻉的优化,左边为不优化的情况下,两次移动构造,右边为编译器优化的场景下连续步骤中的拷⻉合⼆为⼀变为⼀次移动构造。
- 需要注意的是在vs2019的release和vs2022的debug和release,下⾯代码优化为⾮常恐怖,会直接将str对象的构造,str拷⻉构造临时对象,临时对象拷⻉构造ret对象,合三为⼀,变为直接构造。要理解这个优化要结合局部对象⽣命周期和栈帧的⻆度理解,如图3所示。
- inux下可以将下⾯代码拷⻉到test.cpp⽂件,编译时⽤ g++ test.cpp -fno-elide-constructors 的⽅式关闭构造优化,运⾏结果可以看到图1左边没有优化的两次移动。
图三:

2.5.2.3 右值对象赋值,只有拷⻉构造和拷⻉赋值,没有移动构造和移动赋值的场景
- 图4左边展示了vs2019 debug和 g++ test.cpp -fno-elide-constructors 关闭优化环境下编译器的处理,⼀次拷⻉构造,⼀次拷⻉赋值。
- 需要注意的是在vs2019的release和vs2022的debug和release,下⾯代码会进⼀步优化,直接构造要返回的临时对象,str本质是临时对象的引⽤,底层⻆度⽤指针实现。运⾏结果的⻆度,我们可以看到str的析构是在赋值以后,说明str就是临时对象的别名。
图四:

2.5.2.4 右值对象赋值,既有拷⻉构造和拷⻉赋值,也有移动构造和移动赋值的场景
- 图5左边展示了vs2019 debug和 g++ test.cpp -fno-elide-constructors 关闭优化环境下编译器的处理,⼀次移动构造,⼀次移动赋值。
- 需要注意的是在vs2019的release和vs2022的debug和release,下⾯代码会进⼀步优化,直接构造要返回的临时对象,str本质是临时对象的引⽤,底层⻆度⽤指针实现。运⾏结果的⻆度,我们可以看到str的析构是在赋值以后,说明str就是临时对象的别名。
图五:

2.6 右值引用和移动语义在传参中的提效
查看STL文档我们发现C++11以后容器的push和insert系列的接口否增加的右值引用版本;
当实参是一个左值时,容器内部继续调用拷贝构造进行拷贝,将对象拷贝到容器空间中的对象;
当实参是一个右值,容器内部则调用移动构造,右值对象的资源到容器空间的对象上;
把我们之前模拟实现的bit:list拷贝过来,支持右值引用参数版本的push_back和insert;
其实这里还有一个emplace系列的接口(终于来啦),但是这个涉及可变参数模板,我们需要把可变参数模板介绍完以后再介绍emplace系列的接口------涉及引用折叠等内容------
cpp
int main()
{
std::list<std::string> lt;
std::string s1("111111111111111111111");
lt.push_back(s1);
cout << "*************************" << endl;
lt.push_back(std::string("22222222222222222222222222222"));
cout << "*************************" << endl;
lt.push_back("3333333333333333333333333333");
cout << "*************************" << endl;
// 左值move本质授予别人转移你数据资源权限,所以要谨慎
lt.push_back(move(s1));
cout << "*************************" << endl;
return 0;
}
cpp
运行结果:
string(char* str)
string(const string& s) -- 拷⻉构造
*************************
string(char* str)
string(string&& s) -- 移动构造
~string() -- 析构
*************************
string(char* str)
string(string&& s) -- 移动构造
~string() -- 析构
*************************
string(string&& s) -- 移动构造
*************************
~string() -- 析构
~string() -- 析构
~string() -- 析构
~string() -- 析构
~string() -- 析构
list.h:
cpp
#pragma once
namespace jqj
{
// --------------链表节点结构--------------
template<class T>
struct list_node
{
list_node<T>* _next; // 指向下一个节点的指针
list_node<T>* _prev; // 指向前一个节点的指针
T _data; // 节点存储的数据
// --------------节点构造函数--------------
// 左值
list_node(const T& x = T())
:_next(nullptr)
, _prev(nullptr)
, _data(x) // x 节点数据,默认为T类型的默认值
{}
// 右值
list_node(T&& x)
:_next(nullptr)
, _prev(nullptr)
, _data(move(x)) // x 节点数据,默认为T类型的默认值
{}
};
// --------------链表迭代器--------------
// 实现双向迭代器功能,支持前向和后向遍历
template<class T, class Ref,class Ptr> // T 数据类型
// Ref 引用类型(T& 或 const T&)
struct list_iterator
{
// using还具有tepedef没有的功能
// 使用类型别名(C++11新特性)
using Self = list_iterator<T, Ref, Ptr>; // 自身类型
using Node = list_node<T>; // 节点类型
Node* _node; // 当前指向的节点指针
// 迭代器构造函数
list_iterator(Node* node)
:_node(node)
{}
// 迭代器解引用操作
// *it = 1
// Ref 返回节点数据的引用(可读或可写)
Ref operator*() // 解引用,Ref就是reference,引用的意思
{
return _node->_data;
}
// operator*()返回对应数据类型的引用
Ptr operator->() // 返回对应数据类型的指针
{
return &_node->_data;
}
// ++it
// 前向迭代操作
Self& operator++() // Self& 返回递增后的迭代器引用
{
_node = _node->_next;
return *this;
}
Self operator++(int) // Self 返回递增前的迭代器副本
{
Self tmp(*this);
_node = _node->_next;
return tmp;
}
// --it
// 后向迭代操作
Self& operator--() // Self& 返回递减后的迭代器引用
{
_node = _node->_prev;
return *this;
}
Self operator--(int) // Self 返回递减前的迭代器副本
{
Self tmp(*this);
_node = _node->_prev;
return tmp;
}
// 迭代器比较操作
bool operator!=(const Self& s) const // bool 两个迭代器是否不指向同一节点
{
return _node != s._node;
}
bool operator==(const Self& s) const // bool 两个迭代器是否不指向同一节点
{
return _node == s._node;
}
};
//template<class T>
//struct list_const_literator
//{
// using Self = list_const_literator<T>;
// using Node = list_node<T>; Node* _node;
// Node* _node;
// list_const_iterator(Node* node)
// :_node(node)
// { }
// // *it
// const T& operator*()
// {
// return _node->_data;;
// }
// // ++it
// Self& operator++()
// {
// _node = _node->_next;
// return *this;
// }
// Self operator++(int)
// {
// Self tmp(*this);
// _node = _node->_next;
// return *this;
// }
// // --it
// Self& operator--()
// {
// _node = _node->_prev;
// return *this;
// }
// Self operator--(int)
// {
// Self tmp(*this);
// _node = _node->_prev;
// return tmp;
// }
// bool operator!=(const Self& s) const
// {
// return _node != s._node;
// }
// bool operator==(const Self& s) const
// {
// return _node == s._node;
// }
//};
// --------------链表主体类--------------
template<class T>
class list
{
using Node = list_node<T>; // 节点类型别名
public:
// 迭代器类型定义
using iterator = list_iterator<T, T&, T*>; // 普通迭代器
using const_iterator = list_iterator<T, const T&, const T*>; // 常量迭代器
// const T* 只能读数据,不能修改数据
//using iterator = list_iterator<T>;
//using const_iterator = list_const_iterator<T>;
// --------------迭代器访问接口--------------
// 获取指向第一个元素的迭代器
// iterator 指向首元素的迭代器
iterator begin()
{
return iterator(_head->_next);
}
// iterator 指向哨兵节点的迭代器
iterator end()
{
return iterator(_head);
}
// 获取指向第一个元素的常量迭代器
// const_iterator 指向首元素的常量迭代器
const_iterator begin() const
{
return const_iterator(_head->_next);
}
// const_iterator 指向哨兵节点的常量迭代器
const_iterator end() const
{
return const_iterator(_head);
}
// ----------------链表初始化相关-----------------
void empty_init() // 初始化空链表(创建哨兵节点)
{
_head = new Node;
_head->_next = _head;
_head->_prev = _head;
}
// 默认构造函数
list()
{
empty_init();
}
// 初始化列表构造函数
// il 初始化列表
list(initializer_list<T> il)
{
empty_init();
for (auto& e : il)
{
push_back(e);
}
}
// 范围构造函数
// InputIterator 输入迭代器类型
template <class InputIterator>
list(InputIterator first, InputIterator last) // first 范围起始迭代器 // last 范围结束迭代器
{
empty_init();
while (first != last)
{
push_back(*first);
++first;
}
}
// 数量构造函数(size_t版本)
list(size_t n, T val = T()) // val 元素值,默认为T的默认值
{
empty_init();
for (size_t i = 0; i < n; ++i)
{
push_back(val);
}
}
// 数量构造函数(int版本)
list(int n, T val = T()) // val 元素值,默认为T的默认值
{
empty_init();
for (size_t i = 0; i < n; ++i)
{
push_back(val);
}
}
// -------------析构函数-------------
// 清理所有节点并释放哨兵节点
~list()
{
clear();
delete _head;
_head = nullptr;
_size = 0;
}
// -----------拷贝控制函数----------
// lt 要拷贝的源链表
// lt2(lt1)
list(const list<T>& lt)
{
empty_init();
for (auto& e : lt)
{
push_back(e);
}
}
// 拷贝赋值运算符
// lt 要拷贝的源链表
// list<T>& 返回当前链表的引用
// lt1 = lt3
list<T>& operator=(const list<T>& lt)
{
if (this != <)
{
clear();
for (auto& e : lt)
{
push_back(e);
}
}
return *this;
}
////
//list(list<T>& lt)
// list(const list& lt)
//{
// empty_init();
// list tmp(lt.begin(), lt.end());
// swap(tmp);
//}
//// lt1 = lt3
////list<T>& operator=(list<T> tmp)
//list& operator=(list tmp)
//{
// swap(tmp);
//}
// ----------------容量操作---------------
// 交换两个链表的内容
void swap(list<T>& lt) // lt 要交换的另一个链表
{
std::swap(_head, lt._head);
std::swap(_size, lt._size);
}
// 清空链表中的所有元素
// 保留哨兵节点,删除所有数据节点
void clear()
{
iterator it = begin();
while (it != end())
{
it = erase(it);
}
}
//void push_back(const T& x)
//{
// Node* newnode = new Node(x);
// Node* tail = _head->_prev;
// tail->_next = newnode;
// newnode->_prev = tail;
// newnode->_next = _head;
// _head->_prev = newnode;
//}
// -----------------元素访问操作--------------------
// 复用
void push_back(const T& x) // 在链表尾部插入元素,x:要插入的元素值
{
insert(end(), x);
}
// 右值:尾插
void push_back(T&& x)
{
insert(end(), x);
}
// 在链表头部插入元素,x:要插入的元素值
void push_front(const T& x)
{
insert(begin(), x);
}
// // 右值
//void push_front(T&& x)
//{
// insert(begin(), x);
//}
// 删除链表尾部元素
void pop_back()
{
erase(--end());
}
// 删除链表头部元素
void pop_front()
{
erase(begin());
}
// ---------------- 指定位置操作 ----------------
// 在指定位置前插入元素
void insert(iterator pos, const T& x) // pos:插入位置的迭代器,x:要插入的元素值
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* newnode = new Node(x);
// // 连接新节点:prev -> newnode -> cur
// prev newnode cur
prev->_next = newnode;
newnode->_prev = prev;
newnode->_next = cur;
cur->_prev = newnode;
++_size;
}
// 删除指定位置的元素
iterator erase(iterator pos) // iterator 返回指向被删除元素后一个元素的迭代器
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* next = cur->_next;
// 跳过被删除节点:prev -> next
prev->_next = next;
next->_prev = prev;
delete cur;
--_size;
/*return iterator(next);*/
return next; /// 返回下一个节点的迭代器
//两种写法都可以
}
// -------------- 容量信息 ------------------
size_t size() const
{
//size_t n = 0;
//for (auch e : *this)
//{
// ++n;
//}
//return n;
return _size;
}
private:
Node* _head; // 哨兵头节点指针
size_t _size = 0; // 链表元素个数计数器
};
}