I read in accelerated c++ that we should pass lvalue to non-const references. Why is that? As far as i know lvalue is the one which can be modified. Please tell me if it has another definition.
I checked it by writing a simple program:
#include<iostream>
#include<vector>
using namespace std;
vector<double> ret()
{
vector<double> d;
return d;
}
void rec(vector<double> &g)
{
cout<<"entered..."<<endl;
}
int main
{
rec(ret());
}
And error is
invalid initialization of non const reference from r value
What meaning do rvalue and lvalue have here? d is a local variable in ret() and it is passed by value so it does not have dangling issues.
What happens when rec(ret()) is called and
explain to me how rec() sends its argument.
You said,
as far as i know lvalue is the one which cannot be modified.
That is not correct. Traditionally, lvalue stood for a value which can appear on the left hand side of an assignment operator, which means they must be modifiable.
That meaning is still valid today.
Perhaps you are confusing with rvalue, which stood for a value which can appear on the right hand side of assignment operator, which may or may not be modifiable.
That meaning is still valid today.
EDIT
Now that you changed your question to say:
as far as i know lvalue is the one which can be modified.
The answer should be obvious to you. when the argument type of a function is a non-const reference, only lvalues can be passed to such functions, not rvalues.
EDIT 2
Thanks to the comment by #0x499602D2:
For user-defined classes you can use the assignment operator on rvalues as they are like member function calls: A{} = A{}; would compile given an accessible copy/move-assignment operator. I think the term lvalue designates an object that will exist beyond the expression in which it is used, and rvalue meaning the opposite.
Related
(I searched for [c++] "functional programming in c++" book, which give only 4 unrelevant results.)
I'm reading Functional Programming in C++ from Ivan Čukić, and at page 118 there's a sentence which I'm not sure I've understood. The section is about rvalue and lvalue overloads of member functions, and the sentence is the following, where the second overload is the one using the && reference type qualifier:
The second overload will be called on objects from which you're allowed to stead the data -- temporary objects and other rvalue references.
My doubts are these:
the part in italic puzzles me in the first place, as in what else could it be if not a temporary?, but maybe this is just because I still haven't got a firm understanding of what xvalues are;
the word in bold really puzzles me, in that the sentence seems meaningful to me only if I remove that word.
The code below is for support of my understanding.
Indeed, my understanding is that if I say rvalue reference, I'm talking about a function parameter (so it has a name; example: a in the free function f's declaration) declared as rvalue reference to the actual argument, or a variable that I have declared (so it has a name; example: rr) as an rvalue reference to another variable; (fwiw, both referenc-ed entities must be rvalues, otherwise the reference would not bind). In either case, since it has a name, calling the member function f on it, would result in calling the lvalue overload, wouldn't it?
So is there a miswording in the book or am I missing something?
#include <iostream>
struct A {
void f() & { std::cout << "lvalue\n"; } // const & in the book, but it shouldn't make any difference
void f() && { std::cout << "rvalue\n"; }
};
void f(A&& a) { a.f(); } // a is an lvalue (of type rvalue ref to)
int main() {
A a; // "normal" object
A&& rr = A{}; // rvalue reference to a temporary (with life extended)
a.f();
A{}.f(); // only here I expect the rvalue overload to be called, and this is the case
f(A{});
rr.f();
}
the word in bold really puzzles me, in that the sentence seems meaningful to me only if I remove that word.
I agree. IMO to be more precise the sentence should be
The second overload will be called on objects from which you're allowed to stead the data -- rvalues (prvalues or xvalues).
Rvalue reference is used for types, rvalue is used for value categories, they're independent things. In this case, which overload will be called depends on value category, i.e. the object to be called on is an lvalue or rvalue, which has nothing to do with its type.
the part in italic puzzles me in the first place, as in what else could it be if not a temporary?, but maybe this is just because I still haven't got a firm understanding of what xvalues are;
Yes, xvalues are rvalues too. Given int x = 0; std::move(x) is an xvalue but it's not a temporary.
I think there's something I'm not quite understanding about rvalue references. Why does the following fail to compile (VS2012) with the error 'foo' : cannot convert parameter 1 from 'int' to 'int &&'?
void foo(int &&) {}
void bar(int &&x) { foo(x); };
I would have assumed that the type int && would be preserved when passed from bar into foo. Why does it get transformed into int once inside the function body?
I know the answer is to use std::forward:
void bar(int &&x) { foo(std::forward<int>(x)); }
so maybe I just don't have a clear grasp on why. (Also, why not std::move?)
I always remember lvalue as a value that has a name or can be addressed. Since x has a name, it is passed as an lvalue. The purpose of reference to rvalue is to allow the function to completely clobber value in any way it sees fit. If we pass x by reference as in your example, then we have no way of knowing if is safe to do this:
void foo(int &&) {}
void bar(int &&x) {
foo(x);
x.DoSomething(); // what could x be?
};
Doing foo(std::move(x)); is explicitly telling the compiler that you are done with x and no longer need it. Without that move, bad things could happen to existing code. The std::move is a safeguard.
std::forward is used for perfect forwarding in templates.
Why does it get transformed into int once inside the function body?
It doesn't; it's still a reference to an rvalue.
When a name appears in an expression, it's an lvalue - even if it happens to be a reference to an rvalue. It can be converted into an rvalue if the expression requires that (i.e. if its value is needed); but it can't be bound to an rvalue reference.
So as you say, in order to bind it to another rvalue reference, you have to explicitly convert it to an unnamed rvalue. std::forward and std::move are convenient ways to do that.
Also, why not std::move?
Why not indeed? That would make more sense than std::forward, which is intended for templates that don't know whether the argument is a reference.
It's the "no name rule". Inside bar, x has a name ... x. So it's now an lvalue. Passing something to a function as an rvalue reference doesn't make it an rvalue inside the function.
If you don't see why it must be this way, ask yourself -- what is x after foo returns? (Remember, foo is free to move x.)
rvalue and lvalue are categories of expressions.
rvalue reference and lvalue reference are categories of references.
Inside a declaration, T x&& = <initializer expression>, the variable x has type T&&, and it can be bound to an expression (the ) which is an rvalue expression. Thus, T&& has been named rvalue reference type, because it refers to an rvalue expression.
Inside a declaration, T x& = <initializer expression>, the variable x has type T&, and it can be bound to an expression (the ) which is an lvalue expression (++). Thus, T& has been named lvalue reference type, because it can refer to an lvalue expression.
It is important then, in C++, to make a difference between the naming of an entity, that appears inside a declaration, and when this name appears inside an expression.
When a name appears inside an expression as in foo(x), the name x alone is an expression, called an id-expression. By definition, and id-expression is always an lvalue expression and an lvalue expressions can not be bound to an rvalue reference.
When talking about rvalue references it's important to distinguish between two key unrelated steps in the lifetime of a reference - binding and value semantics.
Binding here refers to the exact way a value is matched to the parameter type when calling a function.
For example, if you have the function overloads:
void foo(int a) {}
void foo(int&& a) {}
Then when calling foo(x), the act of selecting the proper overload involves binding the value x to the parameter of foo.
rvalue references are only about binding semantics.
Inside the bodies of both foo functions the variable a acts as a regular lvalue. That is, if we rewrite the second function like this:
void foo(int&& a) {
foo(a);
}
then intuitively this should result in a stack overflow. But it doesn't - rvalue references are all about binding and never about value semantics. Since a is a regular lvalue inside the function body, then the first overload foo(int) will be called at that point and no stack overflow occurs. A stack overflow would only occur if we explicitly change the value type of a, e.g. by using std::move:
void foo(int&& a) {
foo(std::move(a));
}
At this point a stack overflow will occur because of the changed value semantics.
This is in my opinion the most confusing feature of rvalue references - that the type works differently during and after binding. It's an rvalue reference when binding but it acts like an lvalue reference after that. In all respects a variable of type rvalue reference acts like a variable of type lvalue reference after binding is done.
The only difference between an lvalue and an rvalue reference comes when binding - if there is both an lvalue and rvalue overload available, then temporary objects (or rather xvalues - eXpiring values) will be preferentially bound to rvalue references:
void goo(const int& x) {}
void goo(int&& x) {}
goo(5); // this will call goo(int&&) because 5 is an xvalue
That's the only difference. Technically there is nothing stopping you from using rvalue references like lvalue references, other than convention:
void doit(int&& x) {
x = 123;
}
int a;
doit(std::move(a));
std::cout << a; // totally valid, prints 123, but please don't do that
And the keyword here is "convention". Since rvalue references preferentially bind to temporary objects, then it's reasonable to assume that you can gut the temporary object, i.e. move away all of its data away from it, because after the call it's not accessible in any way and is going to be destroyed anyway:
std::vector<std::string> strings;
string.push_back(std::string("abc"));
In the above snippet the temporary object std::string("abc") cannot be used in any way after the statement in which it appears, because it's not bound to any variable. Therefore push_back is allowed to move away its contents instead of copying it and therefore save an extra allocation and deallocation.
That is, unless you use std::move:
std::vector<std::string> strings;
std::string mystr("abc");
string.push_back(std::move(mystr));
Now the object mystr is still accessible after the call to push_back, but push_back doesn't know this - it's still assuming that it's allowed to gut the object, because it's passed in as an rvalue reference. This is why the behavior of std::move() is one of convention and also why std::move() by itself doesn't actually do anything - in particular it doesn't do any movement. It just marks its argument as "ready to get gutted".
The final point is: rvalue references are only useful when used in tandem with lvalue references. There is no case where an rvalue argument is useful by itself (exaggerating here).
Say you have a function accepting a string:
void foo(std::string);
If the function is going to simply inspect the string and not make a copy of it, then use const&:
void foo(const std::string&);
This always avoids a copy when calling the function.
If the function is going to modify or store a copy of the string, then use pass-by-value:
void foo(std::string s);
In this case you'll receive a copy if the caller passes an lvalue and temporary objects will be constructed in-place, avoiding a copy. Then use std::move(s) if you want to store the value of s, e.g. in a member variable. Note that this will work efficiently even if the caller passes an rvalue reference, that is foo(std::move(mystring)); because std::string provides a move constructor.
Using an rvalue here is a poor choice:
void foo(std::string&&)
because it places the burden of preparing the object on the caller. In particular if the caller wants to pass a copy of a string to this function, they have to do that explicitly;
std::string s;
foo(s); // XXX: doesn't compile
foo(std::string(s)); // have to create copy manually
And if you want to pass a mutable reference to a variable, just use a regular lvalue reference:
void foo(std::string&);
Using rvalue references in this case is technically possible, but semantically improper and totally confusing.
The only, only place where an rvalue reference makes sense is in a move constructor or move assignment operator. In any other situation pass-by-value or lvalue references are usually the right choice and avoid a lot of confusion.
Note: do not confuse rvalue references with forwarding references that look exactly the same but work totally differently, as in:
template <class T>
void foo(T&& t) {
}
In the above example t looks like a rvalue reference parameter, but is actually a forwarding reference (because of the template type), which is an entirely different can of worms.
See the code snippet below:
#include<vector>
using std::vector;
int main()
{
vector<int> a;
auto &&it=--a.end();//what?the hint tell me it deduces a lvalue reference type!
}
We all know that a self-defined class with operator -- returns a xvalue when the operand itself is a rvalue, like --Myclass(). Obviously Myclass() is prvalue, so the return value of --Myclass() should also be rvalue(prcisely,xvalue) ,too.
from cppref
a.m, the member of object expression, where a is an rvalue and m is a non-static data member of non-reference type;
So why does the auto deduce lvalue reference in this circumstance?
What's more,the code snippet could be compiled without any error!
Why could a rvalue be binded to a lvalue reference?
And I've come across a confusing error(Not the same as the code snippet above,I'm sure the vector is not empty):Later when I use the it, segment fault happens!
The code that causes segment fault (in the last three lines) This code is the answer for a Chinese online testing PAT,when I submit the answer, it arouses segment fault.
Is it undefined behavior to use lvalue reference to bind a --Myclass() ,and use it later?
We all know that a self-defined class with operator -- returns a rvalue when we write somethin like --Myclass()
No, that's not something we know. Technically, a user defined prefix decrement operator can return either an object, or a reference. In practice, the prefix decrement operator typically returns an lvalue reference.
Obviously Myclass() is prvalue, so the return value of --Myclass() should also be prvalue ,too.
That's not how value categories propagate. You can call a function on a prvalue, and the function can return an lvalue (possibly to *this).
So why does the auto deduce lvalue reference in this circumstance?
Because the decrement operator of the iterator returns an lvalue reference.
Use auto it to fix the problem.
Is it undefined behavior to use lvalue reference to bind a --Myclass() ,and use it later?
Depends on how Myclass::operator--() is declared. If it returns an lvalue reference, then that is UB. If it returns an object, then there is no UB. It is possible to provide both variants overloaded by ref-qualifier.
This is an "universal reference". The variable is not an rvalue reference, but an lvalue into which the rvalue is moved. This is necessary because a reference would not extend the life time of the temporary object.
I have a little C++ question.
On the first pages of Effective Modern C++, there is an example:
class Widget {
public:
Widget(Widget&& rhs);
};
Also, there is a comment: 'rhs is an lvalue, though it has an rvalue reference type'.
I just understood nothing, to be honest. What does it mean 'rhs is an lvalue, but it's type is rvalue reference'?
Keep in mind that there are two distinct things here:
One is related to the type of variables: there are two types of references: lvalue references (&) and rvalue references (&&).
This determines what the function preferentially accepts and is always "obvious" because you can just read it from the type signature (or use decltype).
The other is a property of expressions (or values): an expression can be an lvalue or an rvalue (actually, it's more complicated than that...).
This property is not manifest in the code directly (but there is a rule of thumb, see below), but you can see its effects in the overload resolution. In particular,
lvalue arguments prefer to bind to lvalue-reference parameters, whereas
rvalue arguments prefer to bind to rvalue-reference parameters.
These properties are closely related (and in some sense "dual" to each other), but they don't necessarily agree with each other. In particular, it's important to realize that variables and expressions are actually different things, so formally speaking they aren't even comparable, "apples to oranges".
There is this rule in C++ that, even though you have declared rhs to be an rvalue reference (meaning that it will preferentially match arguments that are rvalues), within the block of move constructor, the variable rhs itself will still behave as an lvalue, and thus preferentially match functions that accept lvalue references.
void test(Widget&&) { std::cout << "test(Widget&&): called\n"; }
void test(Widget&) { std::cout << "test(Widget&): called\n"; }
Widget::Widget(Widget&& rhs) {
// here, `rhs` is an lvalue, not an rvalue even though
// its type is declared to be an rvalue reference
// for example, this will match `test(Widget&)`
// rather than the `test(Widget&&)` overload, which may be
// a bit counter-intuitive
test(rhs);
// if you really want to match `test(Widget&&)`
// you must use `std::move` to "wrap" the variable
// so that it can be treated as an rvalue
test(std::move(rhs));
}
The rationale for this was to prevent unintended moves within the move constructor.
The general rule of thumb is: if the expression has a name (i.e. consists of a single, named variable) then it's an lvalue. If the expression is anonymous, then it's an rvalue. (As dyp noted, this is not technically correct -- see his comment for a more formal description.)
Short and simple explanation :P
Widget(Widget&& rhs);
is a move constructor. It will accept a rvalue as a parameter. Inside the definition of the move constructor, you can refer to the other Widget using the name rhs, therefore it is an lvalue.
For example:
void f(T&& t); // probably making a copy of t
void g()
{
T t;
// do something with t
f(std::move(t));
// probably something else not using "t"
}
Is void f(T const& t) equivalent in this case because any good compiler will produce the same code? I'm interested in >= VC10 and >= GCC 4.6 if this matters.
EDIT:
Based on the answers, I'd like to elaborate the question a bit:
Comparing rvalue-reference and pass-by-value approaches, it's so easy to forgot to use std::move in pass-by-value. Can compiler still check that no more changes are made to the variable and eliminate an unnecessary copy?
rvalue-reference approach makes only optimized version "implicit", e.g. f(T()), and requires the user to explicitly specify other cases, like f(std::move(t)) or to explicitly make a copy f(T(t)); if the user isn't done with t instance. So, in this optimization-concerned light, is rvalue-reference approach considered good?
It's definitely not the same. For once T && can only bind to rvalues, while T const & can bind both to rvalues and to lvalues. Second, T const & does not permit any move optimizations. If you "probably want to make a copy of t", then T && allows you to actually make a move-copy of t, which is potentially more efficient.
Example:
void foo(std::string const & s) { std::string local(s); /* ... */ }
int main()
{
std::string a("hello");
foo(a);
}
In this code, the string buffer containing "hello" must exist twice, once in the body of main, and another time in the body of foo. By contrast, if you used rvalue references and std::move(a), the very same string buffer can be "moved around" and only needs to be allocated and populated one single time.
As #Alon points out, the right idiom is in fact passing-by-value:
void foo(std::string local) { /* same as above */ }
int main()
{
std::string a("hello");
foo(std::move(a));
}
Well, it depends what f does with t, if it creates a copy of it, then I would even go at length of doing this:
void f(T t) // probably making a copy of t
{
m_newT = std::move(t); // save it to a member or take the resources if it is a c'tor..
}
void g()
{
T t;
// do something with t
f(std::move(t));
// probably something else not using "t"
}
Then you allow the move c'tors optimization to happen, you take 't' resources in any case, and if it was 'moved' to your function, then you even gain the non copy of moving it to the function, and if it was not moved then you probably had to have one copy
Now if at later on in the code you'd have:
f(T());
Then ta da, free move optimization without the f user even knowing..
Note that quote: "is void f(T const& t) equivalent in this case because any good compiler will produce the same code?"
It is not equivelent, it is LESS work, because only the "pointer" is transferred and no c'tors are called at all, neither move nor anything else
Taking an const lvalue reference and taking an rvalue reference are two different things.
Similarities:
Neither will cause an copy or move to take place because they are both references. A reference just references an object, it doesn't copy/move it in any way.
Differences:
A const lvalue reference will bind to anything (lvalue or rvalue). An rvalue reference will only bind to non-const rvalues - much more limited.
The parameter inside the function cannot be modified when it is a const lvalue reference. It can be modified when it's an rvalue reference (since it is non-const).
Let's look at some examples:
Taking const lvalue reference: void f(const T& t);
Passing an lvalue:
T t; f(t);
Here, t is an lvalue expression because it's the name of the object. A const lvalue reference can bind to anything, so t will happily be passed by reference. Nothing is copied, nothing is moved.
Passing an rvalue:
f(T());
Here, T() is an rvalue expression because it creates a temporary object. Again, a const lvalue reference can bind to anything, so this is okay. Nothing is copied, nothing is moved.
In both of these cases, the t inside the function is a reference to the object passed in. It can't be modified by the reference is const.
Taking an rvalue reference: `void f(T&& t);
Passing an lvalue:
T t;
f(t);
This will give you a compiler error. An rvalue reference will not bind to an lvalue.
Passing an rvalue:
f(T());
This will be fine because an rvalue reference can bind to an rvalue. The reference t inside the function will refer to the temporary object created by T().
Now let's consider std::move. First things first: std::move doesn't actually move anything. The idea is that you give it an lvalue and it turns it into an rvalue. That's all it does. So now, if your f takes an rvalue reference, you could do:
T t;
f(std::move(t));
This works because, although t is an lvalue, std::move(t) is an rvalue. Now the rvalue reference can bind to it.
So why would you ever take an rvalue reference argument? In fact, you shouldn't need to do it very often, except for defining move constructors and assignment operators. Whenever you define a function that takes an rvalue reference, you almost certainly want to give a const lvalue reference overload. They should almost always come in pairs:
void f(const T&);
void f(T&&);
Why is this pair of functions useful? Well, the first will be called whenever you give it an lvalue (or a const rvalue) and the second will be called whenever you give it a modifiable rvalue. Receiving an rvalue usually means that you've been given a temporary object, which is great news because that means you can ravage its insides and perform optimizations based on the fact that you know it's not going to exist for much longer.
So having this pair of functions allows you to make an optimization when you know you're getting a temporary object.
There's a very common example of this pair of functions: the copy and move constructors. They are usually defined like so:
T::T(const T&); // Copy constructor
T::T(T&&); // Move constructor
So a move constructor is really just a copy constructor that is optimized for when receiving a temporary object.
Of course, the object being passed isn't always a temporary object. As we've shown above, you can use std::move to turn an lvalue into an rvalue. Then it appears to be a temporary object to the function. Using std::move basically says "I allow you to treat this object as a temporary object." Whether it actually gets moved from or not is irrelevant.
However, beyond writing copy constructors and move constructors, you'd better have a good reason for using this pair of functions. If you're writing a function that takes an object and will behave exactly the same with it regardless of whether its a temporary object or not, simply take that object by value! Consider:
void f(T t);
T t;
f(t);
f(T());
In the first call to f, we are passing an lvalue. That will be copied into the function. In the second call to f, we are passing an rvalue. That object will be moved into the function. See - we didn't even need to use rvalue references to cause the object to be moved efficiently. We just took it by value! Why? Because the constructor that is used to make the copy/move is chosen based on whether the expression is an lvalue or an rvalue. Just let the copy/move constructors do their job.
As to whether different argument types result in the same code - well that's a different question entirely. The compiler operates under the as-if rule. This simply means that as long as the program behaves as the standard dictates, the compiler can emit whatever code it likes. So the functions may emit the same code if they happen to do exactly the same thing. Or they may not. However, it's a bad sign if you're functions that take a const lvalue reference and an rvalue reference are doing the same thing.