Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C++ handle a const double& that refers to an int?

Tags:

c++

reference

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!

like image 359
voltrevo Avatar asked Feb 02 '12 23:02

voltrevo


1 Answers

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.

like image 196
ildjarn Avatar answered Oct 07 '22 20:10

ildjarn