想了解右值引用和移动构造函数的请看这篇文章,强烈推荐:架构师大神带你读懂C++ - 微策略中国的文章 - 知乎
https://zhuanlan.zhihu.com/p/93155995
1.非常量引用接受右值的错误例子
首先介绍一下左值(lvalue)和右值(rvalue),C++所有的值必属于左值或者右值,区分左右值有一个简单的方法:若可用"&"符号对表达式取地址,那么为左值,不能为右值。一般来说,临时变量,lambda表达式和字面量都属于右值。如:int i=0; i就是左值,0就是右值。
看如下代码:
#include <iostream>
using namespace std;
int g_constructNum = 0;
int g_copyConstructNum = 0;
int g_deleteNum = 0;
class A {
private:
int m_value;
public:
A(int value) :m_value(value)
{
std::cout << "construct: " << ++g_constructNum << std::endl;
}
A(const A& a)
{
std::cout << "copy construct: " << ++g_copyConstructNum << std::endl;
}
int getValue()
{
return m_value;
}
~A()
{
std::cout << "destruct: " << ++g_deleteNum << std::endl;
}
};
A getA(int value)
{
return A(value);
}
int main()
{
A &a=getA(1);
int testValue = a.getValue();
std::cout << "testValue: " << testValue << std::endl;
return 0;
} 这段代码我在VS2017编译器试了下,没报错,大概是因为VS编译器的优化,让getA(1)返回的对象存续到了函数结束,我在如下2个网上编译器试验都是报错的:
http://ideone.com/
http://coliru.stacked-crooked.com/
报错的结果为:
大意就是非常量左值引用不能绑定右值,因为return A(value);只能产生一个临时的对象,而A &a=getA(1),引用绑定了一个临时对象,在没有优化的编译器,临时对象在A &a=getA(1)这行代码结束后就会销毁,这里就会导致报错。那要怎么解决呢?
2.解决方案
2.1 改为常量引用接受右值
如下代码:
#include <iostream>
using namespace std;
int g_constructNum = 0;
int g_copyConstructNum = 0;
int g_deleteNum = 0;
class A {
private:
int m_value;
public:
A(int value) :m_value(value)
{
std::cout << "construct: " << ++g_constructNum << std::endl;
}
A(const A& a)
{
std::cout << "copy construct: " << ++g_copyConstructNum << std::endl;
}
int getValue() const
{
return m_value;
}
~A()
{
std::cout << "destruct: " << ++g_deleteNum << std::endl;
}
};
A getA(int value)
{
return A(value);
}
int main()
{
const A &a = getA(1);
int testValue = a.getValue();
std::cout << "testValue: " << testValue << std::endl;
return 0;
} 改为常量左值引用,常量左值引用在c98中被称为"万能“引用类型,右值的生命周期和就会和引用相同,输出也会是:
construct: 1
testValue: 1
destruct: 1
所以,不要用非常量左值引用绑定右值
所以一般我们也会用const A&作为函数参数,既能接受左值,也能接受右值,某些情况下你只用引用的话可能传进来的是临时变量就报错了,同时使用const A&传入不会产生拷贝也不会改变传入的变量,非常好以及方便,图片来自:架构师大神带你读懂C++ - 微策略中国的文章 - 知乎
https://zhuanlan.zhihu.com/p/93155995
2.2使用右值引用绑定右值
有的人可能想,我的int getValue()函数不想改为const,又想让程序正常运行,怎么办呢,右值引用就出现了,我们可以通过右值引用来延长临时右值的生命周期,代码如下:
#include <iostream>
using namespace std;
int g_constructNum = 0;
int g_copyConstructNum = 0;
int g_deleteNum = 0;
class A {
private:
int m_value;
public:
A(int value) :m_value(value)
{
std::cout << "construct: " << ++g_constructNum << std::endl;
}
A(const A& a)
{
std::cout << "copy construct: " << ++g_copyConstructNum << std::endl;
}
int getValue()
{
return m_value;
}
~A()
{
std::cout << "destruct: " << ++g_deleteNum << std::endl;
}
};
A getA(int value)
{
return A(value);
}
int main()
{
A &&a=getA(1);//就是修改这行代码就行
int testValue = a.getValue();
std::cout << "testValue: " << testValue << std::endl;
return 0;
}而且,右值引用无法被左值初始化,只能用右值初始化:
int a = 20; // 左值 int&& test1= a; // 非法:右值引用无法被左值初始化 const int&& test2= a; // 非法:右值引用无法被左值初始化
有人的解释为:因为右值引用的目的是为了延长用来初始化对象的生命周期,对于左值,其生命周期与其作用域有关,你没有必要去延长

京公网安备 11010502036488号