c++ - 为什么这里不对引用初始化执行复制初始化?

标签 c++ c++11 c++14

给定

#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/

相关文章:

c++14 - 与库链接导致 char 中缺少 collat​​e facet

c++ - 如何使用三元运算符创建指向多态类的唯一指针?

c++ - std::vector<T> 是 `user-defined type` 吗?

c++ - 当 vector 增长时如何强制执行 move 语义?

c++ - 重新分配 C 样式字符串会导致内存泄漏吗?

c++ - 从 const c++-vector 中检索非常量元素

c++ - Priority_queue 的基于范围的 for 循环

带有可选参数的 C++ 构造函数

c++ - 大类小类

c++ - Visual C++ 中的部分构建与完整构建