【问题标题】:Why do g++ and MS Visual Studio C++ execute the following code differently?为什么 g++ 和 MS Visual Studio C++ 执行以下代码的方式不同?
【发布时间】: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, icc on linux 报告:t.cpp(15): remark #383: value copied to temporary, reference to temporary used 指向那条线。并且表现得像 GCC(打印出它们是不同的)。

标签: c++ reference alias const-correctness


【解决方案1】:

这与我去年报告的一个 Visual C++ 错误有关。请对错误报告进行投票。

https://connect.microsoft.com/VisualStudio/feedback/details/615622/identity-cast-to-non-reference-type-violates-standard

(这里的连接是引用绑定到const int*,这需要从int *进行隐式转换。该转换应该形成一个prvalue,也就是临时的,但在VC++上,它形成一个左值而不是复制.)

【讨论】:

    猜你喜欢
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 2020-10-09
    • 2021-11-12
    相关资源
    最近更新 更多