Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 895
tmoschou Avatar asked Apr 18 '11 15:04

tmoschou


1 Answers

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 from int *. That conversion is supposed to form a prvalue aka temporary, but on VC++ it forms an lvalue instead without making the copy.)

like image 191
Ben Voigt Avatar answered Oct 14 '22 10:10

Ben Voigt