c++ - 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 与在线编译器之间区别的根本原因是什么。
任何回复都非常感谢!
解决方案
如果你用/Wall
flag编译,你会得到编译器自己的答案:
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 方面似乎是一个不错的决定,因为这是一个非常危险的扩展。
演示。
推荐阅读
- swift - 谷歌地图标记在swift 5中显示在路外
- laravel - 覆盖显示这些凭据的默认登录方法与我们的记录不匹配 Laravel 6
- c++ - 使用类级和方法级模板参数定义方法
- javascript - 将 javascript 数组保存到 Postgres 多边形字段中
- apache - 移除 utm_source 参数并用 htaccess 替换 index
- image - 无论对图像宽度所做的更改如何,如何将图像对齐到 SVG 的中心?
- c# - 将屏幕一分为四,篮球比赛
- grep - grep cisco 接口没有任何配置
- php - 在会话销毁时更新数据库
- markup - 关于 Google 电子邮件标记来自生产服务器的重复电子邮件的问题