给定
#include <iostream>
using namespace std;
struct Test {
public:
Test() {
cout << "Default constructor" << endl;
}
Test(const Test &) {
cout << "Copy constructor" << endl;
}
};
int main() {
Test && t1 = Test();
}
为什么在初始化t1时,没有使用Test的拷贝构造函数?来自阅读reference initialization object
似乎是一个临时对象,应该调用复制初始化。或者这是一个类类型表达式?如果是这种情况,有人可以定义什么是类类型表达式(我很难用谷歌搜索)。
最佳答案
Test && t1 = Test();
不创建对拷贝的引用,而是 Test()
生成临时对象和 t1
直接绑定(bind)到那个临时文件(并且临时文件的生命周期延长到 t1
的生命周期)。
2) When a named rvalue reference variable is declared with an initializer
Otherwise, if the reference is either rvalue reference or lvalue reference to const:
If object is an xvalue, a class prvalue, an array prvalue, or a function lvalue type that is either T or derived from T, equally or less cv-qualified, then the reference is bound to the value of the initializer expression or to its base subobject.
关于c++ - 为什么这里不对引用初始化执行复制初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26373923/