【发布时间】:2016-01-27 11:17:32
【问题描述】:
为什么我传递给ClassA 的构造函数的对象被视为右值(临时)?我知道将参数设置为const 会使错误消失,但我想了解发生了什么。
这种行为适用于函数调用,但不适用于构造函数?
#include <iostream>
using namespace std;
class ClassA {
public:
ClassA() {}
ClassA(ClassA&) {}
};
void f(ClassA&) {}
int main() {
ClassA a;
// Invalid initialization of non-const reference of type 'ClassA&' from an
// rvalue of type 'ClassA'
ClassA b = ClassA(a);
// Works fine
f(a);
return 0;
}
【问题讨论】:
-
f(ClassA(a))也无效。