Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

const reference in POD

11 views
Skip to first unread message

mathieu

unread,
Jun 4, 2013, 2:41:38 AM6/4/13
to
While trying to build a compiled time dictionary I discovered the following code. It seems to compile without a single warning on gcc. Could someone please tell me if this is legal, and why ?

$ cat demo.cxx
enum TheType {
INT = 0,
FLOAT
};

struct entry {
TheType type;
const int & val;
};

static const int I0 = 0;
static const float F0 = 0.1f;

static const entry array[] = {
{ INT, I0 },
{ FLOAT, F0 } // {float&} <=> {int&} ?
};

int main(int , char *[])
{
return 0;
}

$ g++ -Wall -pedantic demo.cxx && ./a.out

Thanks

Ian Collins

unread,
Jun 4, 2013, 3:33:02 AM6/4/13
to
mathieu wrote:

*Please wrap your lines!*
I was surprised this didn't produce a warning. Another compiler (Sun
CC) says:

Warning: A class with a reference member lacks a user-defined
constructor, which can lead to errors.

Sound advice!
--
Ian Collins

Francis Glassborow

unread,
Jun 4, 2013, 4:07:13 AM6/4/13
to
Yes, but nonetheless it must then compile the code because the member is
a const & and those can exist even when the initialising type is wrong
as long as a conversion exists. The code is essentially no different to:

int main(){
float const f= 2.0;
int const & i_ref = f;
// the implementation creates a temporary instance of int with the value
2 which it binds to i_ref. The temporary's lifetime will be that of
i_ref. Note that this only applies for const references. and not for
unqualified references

Francis

0 new messages