Is an rvalue reference treated as an lvalue when used within a function?
Asked Answered
E

5

50

I posted this answer: https://mcmap.net/q/355621/-how-is-it-possible-to-get-a-reference-to-an-rvalue Which contains the following code:

void foo(string&& bar){
    string* temp = &bar;

    cout << *temp << " @:" << temp << endl;
}

Is bar an rvalue or an lvalue?

I ask because I obviously cannot take the address of an rvalue, yet I can take the address of an rvalue reference as is done here.

If you can perform any operation on an rvalue reference that you can on an lvalue reference what is the point in differentiating between the two with the "&&" instead of just an "&"?

Emmy answered 12/2, 2015 at 16:54 Comment(9)
The entire point of rvalues is to allow move semantics, they are in most ways (except their type) just references.Vociferant
@Vociferant MikeSeymour's answer helped me understand that. But as with the comment I posted to him, won't that cause trouble if we use it to move construct twice? Say: string temp1(bar), temp2(bar);Emmy
In your example you aren't moving twice, you are copying twice, as bar is an lvalue (its type is an rvalue, weird I know). If you called std::move twice you could run into issues however.Vociferant
@JonathanMee And this double use of bar is precisely why bar is an lvalue - so that such double use doesn't give you issues. It only gets treated as an rvalue when you do it explicitly: std::move(bar).Scrannel
@Vociferant Wait a sec? An rvalue reference is an lvalue, so it won't automatically use the move constructor? I just don't get it. Why do we call it an rvalue reference at all then? The only thing I thought it did was require move construction. But if doesn't even do that...Emmy
@JonathanMee: You are thinking on the wrong side of the fence. An rvalue reference is moved into not moved out of. You know that when your function is called bar will be destroyed, that is what you get. However if you then call a function within yours you don't make that guarantee unless you explicitly say it.Vociferant
"Why do we call it an rvalue reference at all then?" - because it's a reference to an rvalue (or pedantically, to an object denoted by an rvalue expression). That means it refers to a temporary, or a variable that's being explicitly moved from (using std::move or equivalent), so your function can assume it's OK to move from it.Granulite
"If you can perform any operation on an rvalue reference" I suggest you be careful with the terminology here: A name that refers to an lvalue-reference variable has, as an expression, semantics identical to a name that refers to an rvalue-reference variable. In other words, the semantics of a name as an expression are independent from the referenceness of the variable the name refers to. Something like static_cast<int&&>(42) is still an rvalue-expression, whereas let int x = 42; then static_cast<int&>(42) is an lvalue-expression.Predestinate
I think the subtle thing here is, lvalue/rvalue is something beyond type, it's another attribute of an "object", and rvalue is not determined simply by declaration, but by implicitly creating temporary object or calling std::move.Behrens
S
79

Is bar an rvalue or an lvalue?

The question answers itself. Whatever has a name is an lvalue(1). So bar is an lvalue. Its type is "rvalue reference to string", but it's an lvalue of that type.

If you want to treat it as an rvalue, you need to apply std::move() to it.


If you can perform any operation on an rvalue reference that you can on an lvalue reference what is the point in differentiating between the two with the "&&" instead of just an "&"?

This depends on your definition of "perform an operation." An lvalue reference and a (named) rvalue reference are pretty much identical in how you can use them in expressions, but they differ a lot in what can bind to them. Lvalues can bind to lvalue references, rvalues can bind to rvalue references (and anything can bind to an lvalue reference to const). That is, you cannot bind an rvalue to an lvalue reference, or vice versa.

Let's talk about a function parameter of rvalue reference type (such as your bar). The important point is not what bar is, but what you know about the value to which bar refers. Since bar is an rvalue reference, you know for certain that whatever bound to it was an rvalue. Which means it's bound to be destroyed when the full expression ends, and you can safely treat it as an rvalue (by stealing its resources etc.).

If you're not the one doing this directly to bar, but just want to pass bar on, you have two options: either you're done with bar, and then you should tell the next one who receives it that it's bound to an rvalue—do std::move(bar). Or you'll need to do some more things with bar, and so you do not want anyone inbetween stealing its resources from under you, so just treat it as an lvalue—bar.

To summarise it: The difference is not in what you can do with the reference once you have it. The difference is what can bind to the reference.


(1) A good rule of thumb, with minor exceptions: enumerators have names, but are rvalues. Classes, namespaces and class templates have names, but aren't values.

Scrannel answered 12/2, 2015 at 16:59 Comment(12)
@Agnew Which would trigger the second part of my question, what's the point of calling it an rvalue reference then? Why not just call rvalue and lvalue references: references?Emmy
@JonathanMee Tried to explain. Please let me know if it's clearer or needs more.Scrannel
@JonathanMee it is a reference to something that can be safely treated as an rvalue (that is, you can call std::move on it, and you don't risk invalidating an object that might be expected elsewhere to stay valid).Dyad
@jalf You're saying that this is just a hint to the programmer, that he could move it if he wants to? I just don't understand the point of differentiating between an rvalue and lvalue reference then. You can move lvalues too, you just need to know what you are doing.Emmy
@JonathanMee No, it's not just a hint to the programmer. It's a hard rule on the outer side. The difference is not in what you can do with the reference once you have it. The difference is what can bind to the reference.Scrannel
"Whatever has a name is an lvalue." Pedantic remark: Enumerators are rvalues. Is there a simple rule that reconciles this? (e.g. "Names of variables and functions are lvalues")Predestinate
@dyp: The official definition is simple enough: "An lvalue designates a function or object". Names are irrelevant: not all functions and objects have names, and not all named things are lvalues.Granulite
@MikeSeymour Based on this definition, how is std::string{} not an lvalue?Scrannel
@Angew: It doesn't designate an existing object, but creates a temporary object. A conversion that creates a temporary is defined to be an rvalue.Granulite
@MikeSeymour The form of that statement (which is in a part of the Standard that I consider rather informative than normative) is "lvalue => designates function/object". What I'd like to have is some relation "X => lvalue". E.g. what is the difference wrt "designating an object" between f().member vs g().member where class_type& f() vs class_type&& g() (or even class_type g())?Predestinate
Regarding the first paragraph: the type of the expression bar is std::string; the type of the entity bar is std::string&&. Seeing as you also say "it's an lvalue", you seem to be talking about the expression, and therefore its type is in fact just std::string. (Expressions never have reference type)Photochemistry
So, @SamWong had an interesting comment: https://mcmap.net/q/348129/-is-an-rvalue-reference-treated-as-an-lvalue-when-used-within-a-function Is there an answer to why bar would report being an lvalue reference?Emmy
G
16

Is bar an rvalue or an lvalue?

It's an lvalue, as is any expression that names a variable.

If you can perform any operation on an rvalue reference that you can on an lvalue reference what is the point in differentiating between the two with the "&&" instead of just an "&"?

You can only initialise an rvalue reference with an rvalue expression. So you can pass a temporary string to your function, but you can't pass a string variable without explicitly moving from it. This means your function can assume the argument is no longer wanted, and can move from it.

std::string variable;
foo(variable);            // ERROR, can't pass an lvalue
foo(std::move(variable)); // OK, can explicitly move
foo("Hello");             // OK, can move from a temporary
Granulite answered 12/2, 2015 at 17:2 Comment(2)
So you're saying the point of an rvalue reference is to inform the compiler that when it uses that value in a constructor it can use the move constructor? Wouldn't this cause problems if I initialize twice? Say string temp1(bar), temp2(bar);Emmy
@JonathanMee: No, the point of an rvalue reference is that it can only bind to an rvalue. In that example, bar is an lvalue, so both temp variables are initialised with the copy constructor (taking an lvalue reference), not the move constructor (taking an rvalue reference) - preventing any problems which might be caused if the first constructor moved from bar.Granulite
A
0

The expression bar is an lvalue. But it is not an "rvalue reference to string". The expression bar is an lvalue reference. You can verify it by adding the following line in foo():

cout << is_lvalue_reference<decltype((bar))>::value << endl; // prints "1" 

But I agree with the rest of the explanation of Angew.

An rvalue reference, after it has been bound to an rvalue, is an lvalue reference. Actually it is not just for function parameters:

string&& a = "some string";
string&& b = a; // ERROR: it does not compile because a is not an rvalue

If you can perform any operation on an rvalue reference that you can on an lvalue reference what is the point in differentiating between the two with the "&&" instead of just an "&"?

An rvalue reference allows us to do some "lvalue operations" before the rvalue expires.

Aquarius answered 4/7, 2018 at 16:20 Comment(1)
To be clear: saying "the type of bar" is ambiguous as it stands. The token bar could syntactically either be an expression, or not an expression. If it is syntactically an expression, then the type is std::string (not a reference). However if it is syntactically the operand of decltype(id-expression) then the type is std::string&&.Photochemistry
O
0

As a rule of thumb, an id-expression is typically an lvalue, although there are some exceptions to this. The unqualified-id expression bar inside of foo is an lvalue of type string.

Detailed Explanation

bar is an expression. Namely, it is an identifier and thus an unqualified-id. The standard says this in [expr.prim.id.unqual] p3:

The expression is an xvalue if it is move-eligible (see below); an lvalue if the entity is a function, variable, structured binding, data member, or template parameter object; and a prvalue otherwise ([basic.lval]); it is a bit-field if the identifier designates a bit-field.

bar is not move-eligible, so it is an lvalue, not an rvalue (xvalue or prvalue). However, as stated, there are cases where unqualified-ids are rvalues. For example, concepts (C++20) and enumerators (enum constants) are prvalues.

Conveniently, "local variables" (specifically, implicitly movable entities) get moved implicitly in throw, return, and co_return:

std::string foo() {
    std::string s = "awoo";
    return s; // Here, s is an xvalue, not an lvalue.
              // The return statement doesn't copy s.
}

std::string foo(std::string&& s) {
    return s; // Same as above: s is an xvalue, no need to std::move.
}

Note: I am citing the latest working draft, but the rules haven't really changed since C++11.

Rationale

To some, it is surprising and annoying that you need to std::move everywhere to not have things turn into lvalues. However, this is necessary to cover the case where you use some rvalue reference (or anything else) multiple times, such as when you have a mixture of copying and moving:

void take(std::string);

void foo(std::string&& s) {
    take(s);             // first copy
    take(std::move(s));  // then move
}

If s was an rvalue, you would need to "opt out" of move semantics for the first call to take (std::unmove?). Whether one has to move or unmove, they must do something explicitly, and it's better if being forgetful results in unnecessary copies instead of a use-after-move bug.

A way to think about it is that rvalue references give you the right to move from the object (unlike lvalue references), but not the obligation.

Oberheim answered 9/5 at 10:22 Comment(0)
H
-2

In this case named rvalue references are lvalues, while if the input type is const named rvalue reference then it will be rvalue.

#include <string>
#include <iostream>

void foo(const std::string&& bar) { 
    std::string* temp = &bar; // compile error, can't get address
    std::cout << *temp << " @:" << temp << std::endl;
}

int main()
{
    foo("test");
    return 0;
}
Hixon answered 5/12, 2017 at 10:51 Comment(3)
So this does seem to be true. Can you provide a source on this?Emmy
codesynthesis.com/~boris/blog//2012/07/24/…,hope this link is usefulHixon
This is wrong. bar is still an lvalue here; the problem is that &bar has type const std::string *, so this cannot be assigned to std::string* which would discard the const qualifier. If you change the code to const std::string* temp = then it will compile just fine.Photochemistry

© 2022 - 2024 — McMap. All rights reserved.