NRVO什么时候开始?需要满足哪些要求?

我有以下代码。

#include <iostream>    
struct Box {
        Box() { std::cout << "constructed at " << this << 'n'; }
        Box(Box const&) { puts("copy"); }
        Box(Box &&) = delete;
        ~Box() { std::cout << "destructed at " << this << 'n'; }
};
 
auto f() {
    Box v;
    return v; // is it eligible for NVRO?
}

int main() {
    auto v = f(); 
}

上面的代码产生错误。 call to deleted constructor/function in both gcc and clang

但是,如果我更改代码以返回纯右值,则代码有效。

auto f() {
      Box v;
      return Box(); // is it because of copy elision? 
  }
   

为什么会这样?是因为删除移动构造函数吗?如果我将复制和移动构造函数都更改为显式,它也会产生错误吗?

如果标记为已删除,为什么不能简单地使用定义的复制构造函数

编辑:

      compiled with -std=c++20 in both gcc and clang, error.
      compiled with -std=c++17 gcc, compiles.
      compiled with -std=c++17 clang, error.

编辑2:

      clang version: 12.0.0
      gcc version:   11.1

以上是NRVO什么时候开始?需要满足哪些要求?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>