将右值绑定到左值引用
Binding rvalue to lvalue reference
我有以下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
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
。
为什么?
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
,以查看未调用构造函数。
相关文章:
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 将常量指针引用绑定到非常量指针
- 运行时错误:引用绑定到类型为"int"的空指针
- 模板允许左值与右值引用绑定
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 无法将类型"T&"的非常量左值引用绑定到类型"T"的右值 t++ std::atomic<T>
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 将引用绑定到指针的语法是什么?(各种)
- 为什么我不能将常量左值引用绑定到返回 T&&&的函数?
- 为什么 VS 无法将右值引用绑定到指针?
- 出于什么原因,有必要将常量左值引用绑定到右值?
- 为什么此右值引用绑定到左值?
- 使用“void*”将右值引用绑定到左值
- 排序时引用绑定到 'value_type' 类型的 null 指针
- 无法将类型为"类名 &"的非常量左值引用绑定到类型为"类名"的右值
- 引用绑定和复制构造函数/移动构造函数
- 将引用绑定到类型的值会删除限定符 MULTISET
- 无法将类型"int&"的非常量左值引用绑定到类型为"int"的右值
- 多态变体,并将一种类型的引用绑定到另一种类型的引用
- C++17:是编译器为(静态存储持续时间)const引用绑定创建的可修改的临时对象(和存储)