Function returning int&
This question already has an answer here:
int& foo()
is a function returning a (lvalue) reference to an integer.
A reference is like a pointer, but unlike a pointer it has no identity of its own. It is an alias to its target, instead of the address of its target, logically.
Often references are implemented as pointers, but the point of references is that often the compiler can remove their existence entirely. Doing so with pointers is often more difficult, because they have an identity separate from what they refer to.
There is no way in C++ to get the address of a reference. You can get the address of a structure containing a reference, which is so close as makes no difference, but you cannot get the address of the reference itself.
int& foo()
returns a reference to an integer. As an example:
int x=0, y=0;
bool pick_x=true;
int& foo() { if (pick_x) return x; else return y; }
now foo
returns a reference to either of x
or y
depending on the state of pick_x
.
You can use the return value of foo
almost exactly as if it was x
(or y
if !pick_x
.)
lvalue and rvalue come from the days of C. An lvalue is an expression that can go on the left or right of an =
sign, and an rvalue is an expression that can only go on the right of an =
sign.
In many languages, lvalue and rvalue can be expressed in the grammer. In C++, the existence of reference means that the return value of an expression can be a valid thing to assign to, and the existence of overloaded operator=
means that rvalues can sometimes be assigned to. So things get tricky.
In C++11, lvalue reference and rvalue references where added. Each refuse to bind to the other type of expression. There are also forwarding references, which mainly occur in template type deduction.
The semantics of non-const lvalue reference is exactly the same as the semantics of an ordinary pointer, expect that pointer require an *
operator to dereference it, while a reference does not.
So your
int& foo();
foo() = 42;
can be re-expressed in terms of pointers as
int* foo();
*foo() = 42;
If you don't see anything strange or unusual in the second piece of code, then you should not see anything strange or unusual in the first one.
For example
int i;
int &foo() { return i; }
int *bar() { return &i; }
int main()
{
foo() = 42;
assert(i == 42);
*bar() = 24;
assert(i == 24);
}
链接地址: http://www.djcxy.com/p/20602.html
下一篇: 函数返回int&