考虑以下代码片段:
#include <iostream>
using namespace std;
struct Snitch {
Snitch() { cout << "c'tor" << endl; }
~Snitch() { cout << "d'tor" << endl; }
Snitch(const Snitch&) { cout << "copy c'tor" << endl; }
Snitch& operator=(const Snitch&) {
cout << "copy assignment" << endl;
return *this;
}
Snitch(Snitch&&) = delete;
Snitch& operator=(Snitch&&) = delete;
};
Snitch CreateSnitch(bool v) {
Snitch a, b;
if (v) {
return a;
}
return b;
}
int main(int argc, char** argv)
{
Snitch s = CreateSnitch(true);
}
这是 RVO 不起作用的情况,因此在从函数返回对象时应该调用 move 构造。但是随着移动构造被删除,我认为应该调用复制构造函数。相反,我在上述环境中收到以下编译错误:
错误 C2280 'Snitch::Snitch(Snitch &&)': 试图引用已删除的函数
此外,当我添加const
关键字来返回值类型和局部变量时a
,b
它可以工作。我想后一部分编译是因为编译器“理解”没有办法调用移动构造函数并调用复制构造函数。所以,我不明白为什么初始代码无法编译。