c ++使用临时对象右值初始化左值引用以及自动推导
c++ initializing lvalue reference with a temporary object rvalue as well as auto deduction
我在 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 与在线编译器之间的区别的根本原因是什么。
非常感谢任何回复!
如果你用/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.
我在 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 与在线编译器之间的区别的根本原因是什么。
非常感谢任何回复!
如果你用/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.