Sec. 5.4/1 N3797 says:
The result is an lvalue if T is an lvalue reference type or an rvalue
reference to function type and an xvalue if T is an rvalue reference
to object type.
What does it mean? I know what means lvalue expression. I've been trying to find an lvalue reference type definition int the Standard, but I can't. Could you possibly provide it?
The term lvalue reference means a reference with one & in it, e.g.:
int &x = whatever;
int const &y = whatever;
In C++03, lvalue references were the only type of reference. In C++11, rvalue references were added, so the retronym lvalue reference was coined to mean non-rvalue references.
Lvalue references can bind to both lvalues and rvalues (with the restriction about non-const lvalue reference not being able to bind to a temporary object); rvalue references can only bind to rvalues.
Note: universal references may bind to lvalues or rvalues, and after binding they either behave like an lvalue reference, or like an rvalue reference.
There are 2 types of lvalue reference that are described in The C++ Programming Language 4th Edition as follow,
A non-const lvalue reference refers to an object, to which the user of the reference can write.
A const lvalue reference refers to a constant, which is immutable from the point of view of the user of the reference.
in addition,
An rvalue reference refers to a temporary object, which the user of the reference can (and typically will) modify, assuming that the object will never be used again.
Related
The following link provides the 4 forms of reference collapsing (if I'm correct that these are the only 4 forms): http://thbecker.net/articles/rvalue_references/section_08.html.
From the link:
A& & becomes A&
A& && becomes A&
A&& & becomes A&
A&& && becomes A&&
Although I can make an educated guess, I would like a concise explanation for the rationale behind each of these reference-collapsing rules.
A related question, if I might: Are these reference-collapsing rules utilized in C++11 internally by such STL utilities such as std::move(), std::forward(), and the like, in typical real-world use cases? (Note: I'm specifically asking whether the reference-collapsing rules are utilized in C++11, as opposed to C++03 or earlier.)
I ask this related question because I am aware of such C++11 utilities as std::remove_reference, but I do not know if the reference-related utilities such as std::remove_reference are routinely used in C++11 to avoid need for the reference-collapsing rules, or whether they are used in conjunction with the reference-collapsing rules.
The reference collapsing rules (save for A& & -> A&, which is C++98/03) exist for one reason: to allow perfect forwarding to work.
"Perfect" forwarding means to effectively forward parameters as if the user had called the function directly (minus elision, which is broken by forwarding). There are three kinds of values the user could pass: lvalues, xvalues, and prvalues, and there are three ways that the receiving location can take a value: by value, by (possibly const) lvalue reference, and by (possibly const) rvalue reference.
Consider this function:
template<class T>
void Fwd(T &&v) { Call(std::forward<T>(v)); }
By value
If Call takes its parameter by value, then a copy/move must happen into that parameter. Which one depends on what the incoming value is. If the incoming value is an lvalue, then it must copy the lvalue. If the incoming value is an rvalue (which collectively are xvalues and prvalues), then it must move from it.
If you call Fwd with an lvalue, C++'s type-deduction rules mean that T will be deduced as Type&, where Type is the type of the lvalue. Obviously if the lvalue is const, it will be deduced as const Type&. The reference collapsing rules mean that Type & && becomes Type & for v, an lvalue reference. Which is exactly what we need to call Call. Calling it with an lvalue reference will force a copy, exactly as if we had called it directly.
If you call Fwd with an rvalue (ie: a Type temporary expression or certain Type&& expressions), then T will be deduced as Type. The reference collapsing rules give us Type &&, which provokes a move/copy, which is almost exactly as if we had called it directly (minus elision).
By lvalue reference
If Call takes its value by lvalue reference, then it should only be callable when the user uses lvalue parameters. If it's a const-lvalue reference, then it can be callable by anything (lvalue, xvalue, prvalue).
If you call Fwd with an lvalue, we again get Type& as the type of v. This will bind to a non-const lvalue reference. If we call it with a const lvalue, we get const Type&, which will only bind to a const lvalue reference argument in Call.
If you call Fwd with an xvalue, we again get Type&& as the type of v. This will not allow you to call a function that takes a non-const lvalue, as an xvalue cannot bind to a non-const lvalue reference. It can bind to a const lvalue reference, so if Call used a const&, we could call Fwd with an xvalue.
If you call Fwd with a prvalue, we again get Type&&, so everything works as before. You cannot pass a temporary to a function that takes a non-const lvalue, so our forwarding function will likewise choke in the attempt to do so.
By rvalue reference
If Call takes its value by rvalue reference, then it should only be callable when the user uses xvalue or rvalue parameters.
If you call Fwd with an lvalue, we get Type&. This will not bind to an rvalue reference parameter, so a compile error results. A const Type& also won't bind to an rvalue reference parameter, so it still fails. And this is exactly what would happen if we called Call directly with an lvalue.
If you call Fwd with an xvalue, we get Type&&, which works (cv-qualification still matters of course).
The same goes for using a prvalue.
std::forward
std::forward itself uses reference collapsing rules in a similar way, so as to pass incoming rvalue references as xvalues (function return values that are Type&& are xvalues) and incoming lvalue references as lvalues (returning Type&).
The rules are actually pretty simple. Rvalue reference is a reference to some temporary value that does not persist beyond the expression that uses it - in contrast to lvalue reference which references persisting data. So if you have a reference to a persisting data, no matter what other references you combine it with, the actual referenced data is an lvalue - this covers for the first 3 rules. The 4th rule is natural as well - rvalue reference to rvalue reference is still a reference to non-persistent data, hence rvalue reference is yielded.
Yes, the C++11 utilities rely on these rules, implementation provided by your link matches the real headers: http://en.cppreference.com/w/cpp/utility/forward
And yes, the collapsing rules along with template argument deduction rule are being applied when using std::move and std::forward utilities, just like explained in your link.
The usage of type traits such as remove_reference is really depends on your needs; move and forward cover for the most casual cases.
I know that a named reference is an lvalue:
int x = 1;
int& ref1 = x;
int&& ref2 = std::move(x);
I've read the explanation — that is because we can take the address of those ref1 and ref2.
But when we take the address of a reference we actually take the address of the referenced object, don't we? So this explanation doesn't seem to be correct.
So why a named reference is an lvalue?
Per [expr.prim.id.unqual] (8.1.4.1 Unqualified names):
[...] The expression is an lvalue if the entity is a function,
variable, or data member and a prvalue otherwise; it is a bit-field if
the identifier designates a bit-field ([dcl.struct.bind]).
Per [basic]/6:
A variable is introduced by the declaration of a reference other
than a non-static data member or of an object. The variable's name, if
any, denotes the reference or object.
The declaration
int&& ref2 = std::move(x);
is a "declaration of a reference other than a non-static data member." Therefore, the entity denoted by ref2 is a variable. So the expression ref2 is an lvalue.
That explanation is just a simplification. lvalues aren't defined by being "something you can take the address of", but by a specific set of rules about the value category of expressions. Those rules are carefully constructed so as to result in a self-consistent language in which everything fits together reasonably neatly.
That being said, the explanation does rather fit here, if you consider that by writing ref1, you're not really naming "the reference" but the thing being referred to. That's the magic of references: you're supposed to consider them name aliases rather than entities in their own right.
There are some abstraction leaks surrounding this (particularly, member references), but that's the gist.
You ought to forget about notions like "the reference is an lvalue" and instead think about expressions. Objects have types; expressions have value categories.
Here is an explanation from Scott Meyers's book "Effective Modern C++":
In fact, T&& has two different meanings. One is rvalue reference, of course. Such references behave exactly the way you expect: they bind only to rvalues, and their primary raison d’être is to identify objects that may be moved from.
void f(Widget&& param); // rvalue reference
Widget&& var1 = Widget(); // rvalue reference
auto&& var2 = var1; // not rvalue reference
template<typename T>
void f(std::vector<T>&& param); // rvalue reference
template<typename T>
void f(T&& param); // not rvalue reference
The other meaning for T&& is either rvalue reference or lvalue reference. Such references look like rvalue references in the source code (i.e., T&&), but they can behave as if they were lvalue references (i.e., T&). Their dual nature permits them to bind to rvalues (like rvalue references) as well as lvalues (like lvalue references). Furthermore, they can bind to const or non-const objects, to volatile or non-volatile objects, even to objects that are both const and volatile. They can bind to virtually anything. Such unprecedentedly flexible references deserve a name of their own. I call them universal references.
In the last few days I've been trying to grasp an apparently trivial principle behind lvalue/rvalue references. Let us define a new rvalue reference:
int&& x = 12;
x is therefore an lvalue expression of type int&&. Since x is a lvalue, it can be bound to a lvalue reference of the same type, i.e., a lvalue reference of type int&&. Such a lvalue reference would be defined as:
int&& & ref_x = x; // non-working code, just for the sake of explanation
Of course, it is not possible to explicitly define a reference to a reference, and the correct way to perform the binding is as follows:
int& ref_x = x;
C++ Primer reports the following about using references as initializers:
when we use a reference as an initializer, we are really using the
object to which the reference is bound
On the other hand, the lvalue reference must match the type of the lvalue expression. What am I missing? Is reference collapsing involved in this case?
Thanks.
No, x (as an expression) is an expression of type int. The type of the value of an expression is never a reference. In fact, x is also an lvalue, since it is a named thing.
Also, there are no references to references, for the same reason: References bind to values, and values are never references.
If you're ever confused, just keep telling yourself: The value of an expression is always an object type. Whether the value category of an expression is l or r only determines what sort of things the value can bind to; it has no effect on its type.
If I'm not wrong, I think that both a const reference and a rvalue reference can bind to a rvalue. Is there any practical difference between a function that returns the former and a function that returns the latter?
EDIT. I cannot modify the former, but why would I be interested in modifying a rvalue? Does it make sense?
A const lvalue reference can bind to anything. An rvalue reference can only bind to non-const rvalues.
non-const lvalue const lvalue non-const rvalue const rvalue
const T& yes yes yes yes
T&& no no yes no
As you can see, they are very different.
In addition, if a function call returns an lvalue reference, that expression is an lvalue, but if a function call returns an rvalue reference to object, that expression is an xvalue.
A function call is an lvalue if the result type is an lvalue reference type or an rvalue reference to function type, an xvalue if the result type is an rvalue reference to object type, and a prvalue otherwise.
As for when you would want to modify an rvalue - well this is precisely what move semantics are all about. Consider the following function call:
void func(std::string);
func(std::string("Hello"));
The expression std::string("Hello") is an rvalue that creates a temporary object. When initializing the std::string parameter with this rvalue, it will choose the constructor that takes an rvalue reference - the move constructor. This constructor then steals things from the rvalue, which is typically much faster than doing a full copy. We can steal from it because we know it's temporary.
As for when you should return const lvalue references or rvalue references:
Returning a const lvalue reference is most commonly used when you want to give access to read an "internal" object (perhaps a member of a class), but not allow people to modify it.
Returning an rvalue reference is most commonly used (not common at all) when you want to allow calling code to move from an "internal" object (perhaps a member of a class). So instead of moving from a temporary returned object (as they would when returning by value), they literally move from the internal object.
This could also be achieved with a non-const lvalue reference, but then they would have to explicitly std::move it.
So it's not very likely that you'll need to return an rvalue reference.
Not that std::forward has a return type that looks like T&&. However, this is deceptive, because it may or may not be an rvalue reference depending on the type of T. See universal references.
Is there any practical difference between a function that returns the former and a function that returns the latter?
The question seems to be ill-formed. A function that returns a constant lvalue-reference provides access to an object only for reading, while a function that returns an rvalue-reference provides access for moving which means that the caller can take the contents of the referred object and move it to a different object. They are not comparable by any means.
In both cases, the references must point to an object whose lifetime spans beyond the end of the function that is returning it, as otherwise the caller will trip with undefined behavior on using that reference.
I see code on StackOverflow every once in a while, asking about some overload ambiguity with something involving a function like:
void foo(int&& param);
My question is: Why does this even come up? Or rather, when would you ever have "a reference to a reference"? How is that any different from a plain old reference? I've never run across this in real-world code, so I'm curious as to what kind of code would need this.
It's a rvalue reference, Bjarne describes it here.
Shameless copying ("quoting"):
The rvalue reference
An rvalue reference is a compound type
very similar to C++'s traditional
reference. To better distinguish these
two types, we refer to a traditional
C++ reference as an lvalue reference.
When the term reference is used, it
refers to both kinds of reference:
lvalue reference and rvalue reference.
An lvalue reference is formed by
placing an & after some type.
A a; A& a_ref1 = a; // an lvalue reference
An rvalue reference is formed by
placing an && after some type.
A a; A&& a_ref2 = a; // an rvalue reference
An rvalue reference behaves just like
an lvalue reference except that it can
bind to a temporary (an rvalue),
whereas you can not bind a (non const)
lvalue reference to an rvalue.
A& a_ref3 = A(); // Error!
A&& a_ref4 = A(); // Ok
It isn't a reference to a reference: such a thing does not exist.
It is an rvalue reference, a new feature added in C++11.
It's an rvalue reference. Note that the && token used for Boolean AND and rvalue references, and the & token used for bitwise AND and normal references, are different "words" as far as the language can tell.
An rvalue reference is (usually) bound to an object which may be left in an indeterminate state after the rvalue reference is finished, presumably because the object will then be destroyed.
Simply put, binding a variable to an rvalue reference is the usually the last thing you do to it.
Unlike a regular reference but like a const & reference, an rvalue reference can bind to an rvalue (an expression whose address cannot be directly taken). Like a regular reference but unlike a const & reference, an rvalue reference can be used to modify its object.