我正在阅读以下教程:Learn Cpp,在那里,他们举了一个使用r值引用的示例。
#include <iostream>
class Fraction
{
private:
int m_numerator;
int m_denominator;
public:
Fraction(int numerator = 0, int denominator = 1) :
m_numerator{ numerator }, m_denominator{ denominator }
{
}
friend std::ostream& operator<<(std::ostream& out, const Fraction &f1)
{
out << f1.m_numerator << '/' << f1.m_denominator;
return out;
}
};
int main()
{
auto &&rref{ Fraction{ 3, 5 } }; // r-value reference to temporary Fraction
// auto notref=Fraction(4,8);
auto notref{Fraction(4,8)}; //<---MY adding
// f1 of operator<< binds to the temporary, no copies are created.
std::cout << rref << '\n';
std::cout<< notref<<"\n"; //<-- MY adding
return 0;
} // rref (and the temporary Fraction) goes out of scope here
[我正在添加的零件标记是我为这个问题添加的零件。
他们写
作为匿名对象,小数(3,5)通常超出范围在定义它的表达式的末尾。但是,由于我们正在使用它初始化一个r值引用,其持续时间为扩展到块的末尾。然后我们可以使用该r值参考以打印分数的值。
但是,正如您所见,我添加了一个普通变量进行比较,它确实完全相同。分数不超出范围,可以在印刷部件中正常使用。
有什么区别,为什么有人会使用r值引用?
在此示例中,rref仅在返回0后超出范围。它的生存期与notref相同。因此没有区别。