Reputation: 1117
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?
Upvotes: 9
Views: 556
Reputation: 283733
It's related to a Visual C++ bug I reported last year. Please do upvote the bug report.
(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.)
Upvotes: 8