复制初始化不起作用?

Copy initialization not work?

#include <iostream>

using namespace std;

class Test {
public:
    Test() {
        cout << "Default constructor called." << endl;
    }
    Test(Test &obj) {
        cout << "copy constructor called." << endl;
    }
    Test& operator=(const Test &obj) {
        cout << "copy assignment called." << endl;
        return *this;
    }
    ~Test() {
        cout << "destructor called." << endl;
    }
};

Test func(Test test) {
    cout << "func called" << endl;
    return test;
}

int main(int argc, char* argv[]) {
    Test t1;
    Test t2 = func(t1); // No matching constructor for initialization for 'Test'
    return 0;
}

我正在学习C++。我写了一些测试代码来理解复制初始化和复制赋值。现在我不明白为什么第二个作业不能工作。

无法修改 rvalue,在这种情况下,应将其视为常量引用 const Test& obj。因此,当您将 t1 转换为 func 中的 test 时,没问题,因为 t1 是一个左值,但当您从 return value,是一个xvalue(归类为rvalue)。

简而言之,你的复制构造函数的签名是错误的,因为它只接受左值。

第 10 行的以下补丁使代码对我有用。

Test(const Test &obj) {
     ^~~~~

这是 cppreference.com 上关于 copy constructor 的文章。请参阅 语法 部分。
还有 rvalue 篇文章,内容是

An rvalue may be used to initialize a const lvalue reference, in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.



P.S。您也可以使用移动语义 (C++11),它只接受右值。像这样写一个移动构造函数并不难:

Test(Test&& obj) ...

您的复制构造函数允许修改正在复制的对象。

声明

Test t2 = func(t1);

会将 func() 的 return 值存储在一个临时文件中,然后将其复制到 t2 中。但是,这需要一个接受 const 引用的复制构造函数,因为临时对象不能绑定到非 const 引用。

(从技术上讲,允许编译器省略临时文件,但仍然需要为您的代码发出诊断,假设它已经创建了临时文件。换句话说,复制构造函数必须是 const) .

更改您的复制构造函数以接受 const 引用。

Test(Test const &obj) {