Reference to rvalue in C++03

Dec 20, 2011 at 12:21am
This seems to me that it should not work, but in VC++ 2008 express it is compiling and running happily. Shouldn't the compiler be complaining about assinging a reference to an rvalue? I'm a bit out of practice these days, so maybe forgetting something here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class foo
{
public:
};

foo bar()
{
  return foo();
}

int main()
{
  foo & myRef = bar();

  return 0;
}
Dec 20, 2011 at 12:51am
g++ says: "error: invalid initialization of non-const reference of type ‘foo&’ from a temporary of type ‘foo’"

clang++ says: " error: non-const lvalue reference to type 'class foo' cannot bind to a temporary of type 'class foo'"

Change foo & myRef = bar(); to const foo & myRef = bar(); and they are happy.


Last edited on Dec 20, 2011 at 12:56am
Dec 20, 2011 at 2:33am
This is a long-standing bug non-standard language extension of Visual Studio. Like "void main()"

At /W4, Visual Studio 2010 says
warning C4239: nonstandard extension used : 'initializing' : conversion from 'foo' to 'foo &'
A non-const reference may only be bound to an lvalue


(note that this remains illegal in C++11)
Last edited on Dec 20, 2011 at 2:37am
Dec 20, 2011 at 5:16am
Glad to hear - not crazy :) Thanks guys.
Topic archived. No new replies allowed.