I was working on some template code this morning where I used a BOOST_STATIC_ASSERT
to ensure I wasn't creating a reference to the wrong type, as I thought it might be a clearer error message. However when I tried removing the static assert to take a look at the alternative compiler error I was shocked to discover that gcc doesn't even complain when you try to make a const double& referring to an int:
#include <iostream>
int main()
{
int x = 5;
const double& y = x;
std::cout << y << std::endl;
return 0;
}
Compiles, and doesn't even warn:
$ g++ ~/stuff/badRef.cpp -Wall -Wextra -pedantic
$ a.out
5
What's going on here? Is this undefined behaviour? If so why doesn't gcc complain? On my machine int is 4 bytes and a double is 8. That means that when printing a double& it should interpret 8 bytes at that address as a double and print it, yet there is actually a 4 byte int at that location.
Very confused. Help!
const double& y = x;
creates a temporary double
with the value static_cast<double>(x)
, then binds that temporary to y
. The lifetime of the temporary is extended to match the lifetime of y
.
This is completely legal C++ (03 and 11), hence the lack of warning/error.
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