为什么 g++和 MS Visual Studio C++以不同的方式执行以下代码?
我无法理解哪个编译器有问题(如果有)。与 MS Visual Studio C++ 相比,g++ 的以下代码的执行方式有所不同。
#include <iostream>
int main() {
int a = 10; //some random value
int* ptr = &a;
//a temp rvalue of type `const int* const' created in g++
//no temp created in MS Visual Studio
const int* const &alias_for_ptr = ptr;
ptr = 0; //null ptr
if (ptr == alias_for_ptr)
//This will execute in MS Visual Studio C++
//But not in g++
std::cout << "ptr == alias_for_ptr" << std::endl;
else
//This will execute in g++
//But not in MS Visual Studio C++
std::cout << "ptr != alias_for_ptr" << std::endl;
return 0;
}
现在我发现麻烦的一行是
const int* const &alias_for_ptr = ptr;
在 g++ 中,从 ptr 创建了 const int* const 类型的临时右值。但 MSVS 不会创建右值。我在 C++ 标准中找不到任何地方来解释应该发生什么,结果是否具有未定义的行为,或者标准是否将其留给编译者。那么为什么 g++ 和 MS Visual Studio C++ 执行以下代码的方式不同呢?应该发生什么?
I am having trouble understanding which complier is at fault here (if any). The following code is exectued differently of g++ compared with MS Visual Studio C++.
#include <iostream>
int main() {
int a = 10; //some random value
int* ptr = &a;
//a temp rvalue of type `const int* const' created in g++
//no temp created in MS Visual Studio
const int* const &alias_for_ptr = ptr;
ptr = 0; //null ptr
if (ptr == alias_for_ptr)
//This will execute in MS Visual Studio C++
//But not in g++
std::cout << "ptr == alias_for_ptr" << std::endl;
else
//This will execute in g++
//But not in MS Visual Studio C++
std::cout << "ptr != alias_for_ptr" << std::endl;
return 0;
}
Now I figure that the troublesome line is
const int* const &alias_for_ptr = ptr;
and in g++, a temp rvalue of type const int* const
is created from ptr. But MSVS doesn't create an rvalue. And I cant find anywhere in the c++ standard that expalins what should happen, whether the result has undefined behaviour or whether the standard leaves it up to the complier. So why do g++ and MS Visual Studio C++ execute the following code differently? What should happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它与我去年报告的 Visual C++ bug 有关。请对错误报告进行投票。
https://connect .microsoft.com/VisualStudio/feedback/details/615622/identity-cast-to-non-reference-type-violates-standard
(这里的连接是引用绑定到
const int*,它需要从
int *
进行隐式转换。该转换应该形成一个纯右值(也称为临时值),但在 VC++ 上,它会形成一个左值而不进行复制。)It's related to a Visual C++ bug I reported last year. Please do upvote the bug report.
https://connect.microsoft.com/VisualStudio/feedback/details/615622/identity-cast-to-non-reference-type-violates-standard
(The connection here is that the reference binds to
const int*
, which requires an implicit conversion fromint *
. That conversion is supposed to form a prvalue aka temporary, but on VC++ it forms an lvalue instead without making the copy.)