簡體   English   中英

為什么g ++和MS Visual Studio C ++以不同的方式執行以下代碼?

[英]Why do g++ and MS Visual Studio C++ execute the following code differently?

我無法理解哪個編譯器在這里有問題(如果有的話)。 與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 ++以不同的方式執行以下代碼呢? 應該怎么辦?

這與我去年報道的Visual C ++錯誤有關。 請做好bug報告。

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

(這里的連接是引用綁定到const int* ,這需要從int *進行隱式轉換。該轉換應該形成一個prvalue,也就是臨時的,但是在VC ++上,它形成一個左值而不進行復制。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM