VS2017:删除移动构造函数时,复制构造函数不起作用

时间:2019-02-28 11:27:57

标签: c++ rvo nrvo

请考虑以下代码段:

#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关键字以返回值类型和局部变量ab时,它可以工作。我想编译后一部分是因为编译器“了解”没有办法调用move构造函数和调用copy构造函数。 因此,我不明白为什么初始代码无法编译。

0 个答案:

没有答案