将右值绑定到左值引用

Binding rvalue to lvalue reference

本文关键字:引用 绑定      更新时间:2023-10-16

我有以下c ++代码(VS2013(:

#include <iostream>
using namespace std;
class A {
int i;
public:
A(int i) : i(i) {
cout << "Constructor: " << i << endl;
}
A(const A &o) : i(o.i) {
cout << "Copy constructor: " << i << endl;
}
~A() {
cout << "Destructor: " << i << endl;
}
};
A test(const A &a, A b, A *c) {
return *c;
}
int main() {
A b(10);
cout << "START OF TEST" << endl;
test(1, b, &b);
cout << "END OF TEST" << endl;
system("pause");
}

运行代码时,我在"测试开始"和"测试结束"输出之间得到以下输出:

构造函数:1

复制构造函数:10

复制构造函数:10

析构函数:10

析构函数:10

析构函数:1

构建了 3 个对象:1 个使用整数1,2 个使用类A的对象(i = 10(。

值得一提的是,当test函数的参数const A &a更改为A &a(不是常量(时,程序不会编译,给出以下错误:

错误 C2664:"A 测试(A &,A,A *(":无法将参数 1 从 "int"到"A &">

如何解释这种行为?

具体说来:

  1. 为什么发送整数1test使 A 的参数构造函数A(int i)工作(并且仅在使用const时(?

  2. 为什么 A 的复制构造函数 A(const A &o( 工作两次?(调用test时发生一次运行,返回*c时发生另一次运行(。

好吧,使用第一个参数调用1test会导致创建类型Arvalue。右值可以分配给const lvalue reference,但不能分配给纯lvalue引用。如果希望它在不使用const的情况下进行编译,则必须指定参数是rvalue引用。

g++错误的信息量更大一些:

error: cannot bind non-const lvalue reference of type ‘A&’ to an rvalue of type ‘A’
test(A(1), b, &b);

rvalue可以分配给rvalue referencelvalue reference to const

  • 为什么?rvalues是临时对象或文本。如果此代码是合法的

    int &r= 5

    然后,您将能够修改5. 另一方面,lvalue references to const禁止对它们引用的对象进行任何更改,因此您可以将它们绑定到rvalue


const A& x = 1; //compile
x = 2;         //error!
A&& xxx = 1; //compile
A& xx  = 1; //does not compile.

关于第二个问题。您正在从test返回A的副本*c因此触发c副本的构造。 尝试从test返回引用A,以查看未调用构造函数。