Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
I was reading an article on rvalues in order to understand universal references from the new C++ Standard and found the following as an example of lvalue
// lvalues:
//
int i = 42;
i = 43; // ok, i is an lvalue
int* p = &i; // ok, i is an lvalue
int& foo();
foo() = 42; // ok, foo() is an lvalue
int* p1 = &foo(); // ok, foo() is an lvalue
What does int& foo();
mean here?
Say the body of foo was this:
int & foo()
{
static int i = 0;
return i;
}
foo() = 30;
That would set the static int, i, to 30;
A more practical example is a class returning a reference to itself
class foo
{
public:
foo() {}
foo& addString() {
/* AddString */
return *this;
}
foo& subtractSomething() {
/* Subtract Something */
return *this;
}
}
Then use it like:
foo f;
f.addString().subtractSomething();
class operators do this - so you can do this:
foo a, b c;
foo d = a+b+c;
Where the + operator is defined as:
foo & operator+(const foo& f)
int& foo();
Declares a function that returns a reference to an int
. You can see it as similar to
int* foo();
Except that the return value cannot be null.
The syntax is a bit different, though, since int* foo();
would be used as *(foo()) = 42;
, and int& foo();
as foo() = 42
.
You can read more about references in the FAQ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With