【发布时间】:2020-05-13 00:06:35
【问题描述】:
我正在阅读以下教程: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
标记“我的添加”的部分是我为这个问题添加的部分。
他们会写
作为一个匿名对象,Fraction(3, 5) 通常会超出范围 在定义它的表达式的末尾。然而,由于 我们正在用它初始化一个 r 值引用,它的持续时间是 一直延伸到区块结束。然后我们可以使用该 r 值 参考打印分数的值。
但是,如您所见,我添加了一个普通变量进行比较,它完全相同。分数没有超出范围,可以正常用于打印部分。
有什么区别?为什么有人会使用 r 值参考?
【问题讨论】:
-
rref和notref除了decltype(id)的行为外完全相同。参考部分指的是它是如何被初始化的,而不是它在创建后的行为方式。这种rref的使用并不常见;最常见的做法是使用右值或转发引用作为函数参数
标签: c++ c++11 rvalue-reference