1.c++11的发展历史
2.初始化列表
2.1c++98中一般数组和结构体可以用{}进行初始化。
struct Point
{
int _x;
int _y;
};
int main()
{
int array1[] = { 1,2,3,4,5 };
int array2[] = { 0 };
Point p = { 1,2 };
return 0;
}
2.2c++11中的{}
c++11以后想要统一初始化方式,试图实现一切对象皆可使用{}初始化,{}初始化也叫列表初始化。
内置类型支持,自定义类型也支持,自定义类型本质是类型转换,中间会产生临时对象,最后优化了以后变成直接构造。
{}初始化过程中,可以省略掉=。
c++11列表初始化的本意是实现一个大一统的初始化方式,其次它在有些场景带来了不少便利,比如容器push/insert多参数构造的对象时,{}初始化会很方便。
#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}直接构造初始化
//运行一下,我们可以验证上面的理论,发现是没调用拷贝构造的
Date d1 = { 2025,1,1 };
//这里d2引用的是{2024,7,29}构造的临时对象
const Date& d2 = { 2014,7,29 };
//需要注意的是c++98支持单参数时类型
Date d3 = { 2025 };
Date d4 = 2025;
cout << "********************" << endl;
//可以省略掉=
Point p1{ 1,2 };
int x2{ 2 };
Date d6{ 2024,7,29 };
const Date& d7{ 2024,7,29 };
//不支持,只有{}初始化,才能省略=
//Date d8 2025;
cout << "********************" << endl;
vector<Date> v;
v.push_back(d1);
cout << "********************" << endl;
v.push_back(Date(2025, 1, 1));
cout << "********************" << endl;
//比起有名对象和匿名对象传参,这里{}更有性价比
v.push_back({ 2025,1,1 });
return 0;
}
2.3c++11中的std::initializer_list
{}初始化已经很方便,但是对象容器初始化还是不太方便。比如一个vector对象,我想用N个值去构造初始化。那我们得实现很多个构造参数才能支持。
vector<int> v1={1, 2, 3}; vector<int> v2={1, 2, 3, 4, 5};
c++11库提出了一个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的构造函数支持的。
//STL中的容器都增加了一个initializer_list的构造
//vector(initializer_list<value_type> il, const allocator_type& allopc = allocator_type());
//list(initializer_list<value_type> il, const allocator_type& alloc=alloctor_type());
//map(initializer_list<value_type> il,const key_compare& cope=key_compare(),const allocator_type& alloc=alloctor_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 };
//这种写法在C++中是错误的。
// 原因是列表初始化不能直接用于构造一个临时对象以初始化一个引用。
// 引用的初始化必须直接引用一个已存在的对象。
//vector<int>& v3 = { 1,2,3,4,5 };
//使用const延长临时对象的声明周期
const vector<int>& v3 = { 1,2,3,4,5 };
//这里是pair对象的{}初始化和map的initializer_list构造结合到一起用了
map<string, string> dict = { {"sort","排序"},{"string","字符串"} };
//initializer_list版本的赋值支持
v1 = { 10,20,30,40,50 };
return 0;
}
3.右值引用与移动语义
c++98的c++就有引用的语法,而c++11新增了右值引用语法特性,c++11之前我们学习的引用叫左值引用。无论是左值引用还是右值引用,都是给对象取别名。
3.1左值和右值
左值是一个表达数据的表达式(如变量名或解引用的指针),一般是有持久状态,储存在内存中,我们可以获取它的地址,左值可以出现在赋值符号的左边,也可以出现在赋值符号右边。定义时const修饰的左值,不能给它赋值,但可以取它的地址。
右值也是一个表达数据的表达式,要么是字面量常量,要么是表达式求值过程中创建的临时对象,右值可以出现在赋值符号的右边,但不能出现在赋值符号的左边,右值不能取地址。
值得一提的是,左值的英文简写是lvalue,右值的英文简写是rvalue。传统认为它们分别是left value, right value的简写。现代c++中,lvalue被解释为locator value的简写,可意为存储在内存中,有明确存储地址可以取地址的对象。而rvalue被解释为read value,指的是哪些可以提供数据值,但不可以寻址,例如,临时变量,字面量常量,存储在寄存器中的变量等,也就是说左值和右值的核心区别在于能否取地址。
#include<iostream>
using namespace std;
int main()
{
//左值:可以取地址
//以下的p, b, *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;
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("111111");
//cout << &10 << endl;
//cout << &(x + y) << endl;
//cout << &(fmin(x + y)) << endl;
//cout << &string("1111111") << ednl;
return 0;
}
3.2左值引用和右值引用
Type& r1 = x;Type&& rr1 = y;第一个语句就是左值引用,左值引用就是给左值取别名。第二个语句就是右值引用,同样的道理,右值引用就是给右值取别名。
左值引用不能引用右值,但是const左值引用可以引用右值。
右值引用不能引用左值,但是右值可以引用move(右值)。
template typename remove_reference::type&& move (T&& arg);
move是一个库里面的函数模板,本质内部进行强制类型转换。
需要注意的是变量表达式都是左值属性,也就意味着一个右值被右值引用绑定后,右值引用变量表达式的属性是左值。
语法层面看,左值引用和右值引用都是取别名,不开空间。从汇编底层的角度看下面代码中r1和rr1汇编层实现,底层都是用指针实现的,没什么区别。底层汇编等实现和上层语法表达的意义有时是相背离的,所以不要到一起去理解,相互佐证,这样反而是陷入迷途。
template <class _Ty>
remove_reference_t<_Ty>&& move(_Ty&& _Arg)
{
//foreard _Arg as movable
return static_cast<remove_reference_t<_Ty>&&>(_Arg);
}
#include<iostream>
using namespace std;
int main()
{
//左值:可以取地址
//以下的p, b, *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("111111");
//右值引用不能直接引用左值,但是右值引用可以引用move(左值)
int&& rrx1 = move(b);
int*&& rrx2 = move(p);
int&& rrx3 = move(*p);
string&& eex4 = 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;
}
3.3引用延长寿命周期
右值引用可用于为临时对象延长生命周期,const左值引用也能延长临时对象生命周期,但这些对象无法被修改。
int main()
{
std::string s1 = "Test";
//std::string&& r1=s1; //错误:右值引用不能绑定到左值
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;
}
3.4左值和右值的参数匹配
c++98中,我们实现一个const的左值引用作为参数的函数,那么实参传递左值和右值都可以匹配。
c++11以后,我们重载左值引用,const左值引用,右值引用作为参数的f函数,那么实参是左值,会匹配f(左值引用),实参是const左值会匹配f(const左值),实参是右值会匹配(右值引用)。
右值引用变量在用于表示式时属性是左值,在右值引用的场景中有其设计的价值。
#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&&)
//右值引用变量在用于表示式时是左值
//x是一个右值引用,绑定到字面量1(右值),
//但x本身是一个具名变量,具有持久的内存地址,因此在表达式中x是左值
int&& x = 1;
f(x);//调用f(int& x)
f(std::move(x));//调用f(int&& x)
return 0;
}
3.5右值引用和移动语义的使用场景
3.5.1左值引用主要使用场景回顾
左值引用主要使用场景是在函数中左值引用传参和左值引用传返回值时减少拷贝,同时还可以修改实参和修改返回值的价值。左值引用已经解决大部分场景的拷贝效率问题,但是有些场景不能使用传左值引用返回,如addstring和geneate函数,C++98中的解决方案只能是被迫使用输出型参数解决。那么c++11以后这里就可以使用右值引用做返回值解决吗?显然是不可能的,因为这里的本质是返回对象是一个局部对象,函数结束这个对象就析构了,右值引用返回也无法解决对象已经析构销毁的事实。
class Solution {
public:
//传值返回需要拷贝
string addString(string num1, string num2)
{
string str;
int end1 = num1.size() - 1, end2 = num2.size() - 1;
//进位
int next = 1;
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;
}
};
3.5.2移动构造和移动赋值
移动构造函数是一种构造函数,类似拷贝构造函数,移动构造函数要求第一个参数是该类类型的引用,但是不同的是要求这个参数是右值引用,如果还有其他参数,额外的参数必须有缺省值。
移动赋值是一个赋值运算符的重载,它和拷贝赋值构成函数重载,类似拷贝赋值函数,移动赋值函数要求第一个参数是该类类型的引用,但是不同的是要求这个参数是右值引用。
对于像string/vector这样的深拷贝的类或者包含深拷贝的成员变量的类,移动构造和移动赋值才有意义,因为移动构造和移动赋值的第一个参数都是右值引用的类型,它的本质是要"窃取"引用的右值对象的资源,而不是像拷贝构造和拷贝赋值那样去拷贝资源,从而提高效率,下面的Claire::string样例实现了移动构造和移动赋值,我们需要结合场景理解。
#include<iostream>
#include<assert.h>
#include<string.h>
#include<algorithm>
using namespace std;
namespace Claire
{
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)
:_str(nullptr)
{
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;
};
}
int main()
{
Claire::string s1("xxxxx");
//拷贝构造
Claire::string s2 = s1;
//构造+移动构造,优化后直接构造
Claire::string s3 = Claire::string("yyyyy");
//移动构造
Claire::string s4 = move(s1);
cout << "**************" << endl;
return 0;
}