首页 > 解决方案 > c ++使用临时对象右值以及自动推导初始化左值引用

问题描述

我在 MSVC 中使用 /std:c++17 成功执行以下语句,没有任何编译错误。

class A {
 public:
  A() {
    std::cout << "default constructor." << std::endl;
  }
  A(const A&) {
    std::cout << "const A&" << std::endl;
  }
  A(A&&) {
    std::cout << "A&&" << std::endl;
  }
  int a;
};

A& a = A();
auto& b = A();

我不敢相信左值引用可以用右值初始化,也可以用于 auto&。

但是我已经用一些在线编译器进行了测试,他们预期会发出编译错误。

我真的很想知道 MSVC 与在线编译器之间区别的根本原因是什么。

任何回复都非常感谢!

标签: c++visual-c++c++17

解决方案


如果你用/Wallflag编译,你会得到编译器自己的答案:

warning C4239: nonstandard extension used: 'initializing': conversion from 'A' to 'A &'
note: A non-const reference may only be bound to an lvalue

warning C4239: nonstandard extension used: 'initializing': conversion from 'A' to 'A &'
note: A non-const reference may only be bound to an lvalue

即,根据 C++17 标准,该程序确实格式错误,但利用了 MSVC 非标准扩展。请注意,您的程序被拒绝/std:latest,这在 MSVC 方面似乎是一个不错的决定,因为这是一个非常危险的扩展。

演示


推荐阅读