我有以下 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");
}
运行代码时,我在“START OF TEST”和“END OF TEST”输出之间得到以下输出:
Constructor: 1
Copy constructor: 10
Copy constructor: 10
Destructor: 10
Destructor: 10
Destructor: 1
构建了 3 个对象:1 个使用整数 1
, 和 2 使用类 A
的对象(我 = 10)。
值得一提的是,当 test
函数的参数 const A &a
更改为 A &a
(不是常量),程序编译不通过,报错如下:
Error C2664: 'A test(A &,A,A *)' : cannot convert argument 1 from 'int' to 'A &'
如何解释这种行为?
具体来说:
为什么发送一个整数
1
至test
制作A的参数构造函数A(int i)
工作(并且仅当使用const
时)?为什么 A 的复制构造函数 A(const A &o) 工作了两次? (调用
test
时发生一次运行,返回*c
时发生另一次运行)。
最佳答案
好吧,使用第一个参数 1
调用 test
会导致创建类型为 A
的 rvalue
。右值可以分配给 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 reference
或 lvalue reference to const
。
这是为什么?
右值
是临时对象或文字。如果这段代码是合法的int &r
= 5然后你就可以修改
5
了。 另一方面,对 const 的左值引用
禁止对它们引用的对象进行任何更改,因此您可以将它们绑定(bind)到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
以查看未调用构造函数。
关于c++ - 将右值绑定(bind)到左值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44884560/