【发布时间】:2011-04-18 15:04:10
【问题描述】:
我无法理解是哪个编译器出了问题(如果有的话)。与 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++ 中,const int* const 类型的临时右值是从 ptr 创建的。但是 MSVS 不会创建右值。而且我在 c++ 标准中找不到任何地方来解释应该发生的事情,结果是否具有未定义的行为,或者标准是否将其留给编译器。那么为什么 g++ 和 MS Visual Studio C++ 执行以下代码的方式不同呢?应该怎么办?
【问题讨论】:
-
FWIW,
iccon linux 报告:t.cpp(15): remark #383: value copied to temporary, reference to temporary used指向那条线。并且表现得像 GCC(打印出它们是不同的)。
标签: c++ reference alias const-correctness