Discussion:
Initialization of reference to non-const
(too old to reply)
ali
2006-06-10 19:47:43 UTC
Permalink
Can anyone please explain to me the rational behind the decision that
I cannot bind a reference to non-const to a temporary?

void bar_01(Foo& f) {}
Foo bar_02() { return Foo(); }

bar_01(Foo());
Foo& f = bar_02();

Both of the two last lines give me on Comeau/gcc/...

error: initial value of reference to non-const must be an lvalue

(while, btw Vis C++ 8 happily goes along with it).

After quite some search in the standard - when I read the following
lines I couldn't figure out why the above code does not correspond
with it:

"A variable declared to be a T&...shall be initialized by an object,
or function, of type T or by an object that can be converted into
a T." 8.5.3(1)

- but finally I've found in "References", 8.5.3(5)

"- Otherwise, the reference shall be to a non-volatile const type."

Again, what is the reasoning behind it and are there other places in
the standard which make it clear (in the sense of clearer) that my
given code is ill-formed?

Thanks,
Ali


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Bo Persson
2006-06-11 21:37:01 UTC
Permalink
Post by ali
Can anyone please explain to me the rational behind the decision that
I cannot bind a reference to non-const to a temporary?
void bar_01(Foo& f) {}
Foo bar_02() { return Foo(); }
bar_01(Foo());
Foo& f = bar_02();
The reason is that you can update the non-const parameter, but will
lose the updates if it is a temporary. The implicit convertions of C
types also plays tricks, and creates temporaries in unexpected places.

void inc(float& x)
{ x += 1; }

int i = 0;
float y = 0;

inc(y); // works
inc(i); // doesn't work

and what about

inc(5.0f);
Post by ali
Both of the two last lines give me on Comeau/gcc/...
error: initial value of reference to non-const must be an lvalue
(while, btw Vis C++ 8 happily goes along with it).
That's a compiler extension, on by default. You can disable it with
/Za.


Bo Persson



[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Valentin Samko
2006-06-11 21:31:36 UTC
Permalink
Post by ali
Can anyone please explain to me the rational behind the decision that
I cannot bind a reference to non-const to a temporary?
This is addressed in the "rvalue references" proposal, take a look at
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1690.html

--

Valentin Samko - http://www.valentinsamko.com

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Loading...