tmo*_*hou 9 c++ alias reference const-correctness
我无法理解哪个编译器在这里有问题(如果有的话).与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;
}
Run Code Online (Sandbox Code Playgroud)
现在我认为麻烦的线是
const int* const &alias_for_ptr = ptr;
Run Code Online (Sandbox Code Playgroud)
在g ++中,类型的临界值const int* const
是从ptr创建的.但MSVS不会创建右值.而且我无法在c ++标准中的任何地方找到应该发生的事情,结果是否有未定义的行为或标准是否将其留给编译器.那么为什么g ++和MS Visual Studio C++以不同的方式执行以下代码呢?应该怎么办?
这与我去年报道的Visual C++错误有关.请做好bug报告.
(此处的连接是引用绑定到的const int*
,这需要从中进行隐式转换int *
.该转换应该形成一个prvalue,也就是临时的,但在VC++上它会形成一个左值,而不会复制.)