g++ 可以,但是 clang 不行:将右值返回到左值

问题描述 投票:0回答:1

我有以下示例,使用 g++ 可以,但使用 clang++ 可以使用 C/E。 我想知道他们中间谁是正确的?

#include <iostream>

class MyClass {
public:
  MyClass() {
    std::cout << "DC" << std::endl;
  }
  MyClass(const MyClass&) {
    std::cout << "CC" << std::endl;
  }
  MyClass(MyClass&&) {
    std::cout << "MC" << std::endl;
  }
  ~MyClass() {
    std::cout << "Destruct C" << std::endl;
  }
};

template<typename T>
decltype(auto) func4(T&& x) {
  return x; // g++ - fine ; clang++ - ERROR
}

int main() {
  MyClass mc;
  func4(std::move(mc));
  return 0;
}

错误消息:

$ clang++-12 --std=c++14 ./ex_001_decltype_auto.cpp -o ./ex_001_decltype_auto
./ex_001_decltype_auto.cpp:42:10: error: rvalue reference to type 'MyClass' cannot bind to lvalue of type 'MyClass'
  return x;
c++ g++ clang++
1个回答
0
投票

从 C++23 开始这是合法的,请参阅P2266R3。 GCC 13 和 Clang 13 确实实现了它(两者都接受 C++23 模式下的代码),而 MSVC 还没有。

本文(除其他外)扩展了隐式移动(当返回不是引用或右值引用的局部变量时发生),无论返回类型如何,它都适用,而它过去只在返回非引用时起作用。

© www.soinside.com 2019 - 2024. All rights reserved.