Reputation: 22570
I was reading a blog about c++11 rvalue references by Thomas Becker, and the following syntax near the bottom of the page really confuses me.
int& foo();
foo() = 42; // ok, foo() is an lvalue
What exactly is foo
? A function pointer that returns a int
; an object?
If a function object, how can you assign a value to it, and why is foo
a lvalue?
Upvotes: 0
Views: 119
Reputation: 16777
Every function has at least one return expression. Let's look at function calling using the following incomplete, simplified description :
Assume your function signature is T f();
, with one return expression return e;
. For the sake simplicity, lets also assume that e
and T
have the same type after removing references and const
-ness. In this situation, you can go to your function call location and replace the call f()
with (T)e
, to understand what's going on.
int& f(){....; return e;}
.
.
.
f() = 5;
becomes
(int&)e = 5;
Of course, if converting e
to an lvalue reference(int&
) was invalid, the compiler will throw an error.
Upvotes: 0
Reputation: 109289
int& foo();
declares a function foo
that takes no arguments and returns a reference to an int
. For example,
#include <iostream>
int a = 0;
int& foo();
int main()
{
std::cout << a << std::endl;
foo() = 42;
std::cout << a << std::endl;
}
int& foo() { return a; }
Output:
0
42
Upvotes: 5
Reputation: 119641
foo
is a function with return type int&
. The line
int& foo();
simply declares the function, but does not define it.
When foo
is called, the result is an lvalue of type int
. Therefore you can assign to it: foo() = 42;
Upvotes: 3