【问题标题】:c++ initializing lvalue reference with a temporary object rvalue as well as auto deduction [duplicate]c ++使用临时对象右值初始化左值引用以及自动推导[重复]
【发布时间】:2021-03-21 12:23:39
【问题描述】:

我在 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


    【解决方案1】:

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

    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 方面似乎是一个不错的决定,因为这是一个非常危险的扩展。

    DEMO.

    【讨论】:

      猜你喜欢
      • 2015-03-08
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多