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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With