Take a look at the following code:
struct s
{
s& operator+() {return*this;}
};
void foo(s &) {}
s bar() {}
int main()
{
foo(bar()); //comp error
foo(+bar()); //ok
}
I think the two lines in main() should be equivalent, because the compiler optimizes away operator+(), right? What sense does it make to accept one but not the other?
The line foo(bar()) is trying to bind an rvalue of type s (the temporary returned by bar()) to a non-const lvalue reference to s (the argument of foo()). This is illegal, hence the compilation error. rvalues can only be bound to rvalue references or to const lvalue references.
The expression +bar(), on the other hand, returns an lvalue reference (that's the return type of operator + ()), which can be bound to the lvalue reference parameter of foo().
Beware though: you are returning an lvalue reference to a temporary here. While using it inside foo() is still safe (the temporary will be destroyed when the full-expression in which it is created is completely evaluated, so after foo() returns), you would get Undefined Behavior if you stored that reference somewhere and dereferenced it later.
Therefore, instead of regarding this as a "solution to a compilation error", you should consider it a way to blindfold the compiler so you are free to sneak into big troubles.
Related
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.
Can someone help me to understand why the following code causes a warning
struct A
{
A() : _a( 0 ) {}
const int& _a;
};
int main()
{
A a;
}
with warning
warning: binding reference member '_a' to a temporary value [-Wdangling-field]
A() : _a( 0 ) {}
but this code, where std::move is used to initialize the member _a, does not:
struct A
{
A() : _a( std::move(0) ) {}
const int& _a;
};
int main()
{
A a;
}
Aren't 0 and std::move( 0 ) both r-values?
This is an expression:
0
It's a very small expression, true. But it is an expression.
Once the expression is evaluated, it goes away. It disappears. Joins the choir invisible. Goes to meet its maker. It becomes an ex-expression.
It is true that binding a const reference to a temporary extends the scope of the temporary value until the end of the enclosing scope.
But in this case, the scope of the expression is the constructor. When the constructor is done, the temporary value gets destroyed.
Your compiler noticed the fact that a const reference to the expression still continues to exist, though, as a class member. Your compiler is advising you that using the class member will now result in undefined behavior. Your compiler wants to be your friend. Your compiler doesn't want you to write buggy code, so you're getting some free, friendly advice, from your compiler.
In the other case, you have added some additional code which is slightly more complicated. It is still undefined behavior, but the code is now complex enough that the compiler cannot see that undefined behavior results. But it's still the same bug.
A compiler will try to warn you of potential problems, when the compiler sees them. Unfortunately, the compiler cannot find all possible potential problems, every time. But, when it's obvious, the compiler will let you know.
Their return values are not exactly the same.
From cppreference.com
In particular, std::move produces an xvalue expression that identifies
its argument t. It is exactly equivalent to a static_cast to an rvalue
reference type.
Now, looking at rvalue references, we see that object "0" in second example can live longer:
An rvalue may be used to initialize an rvalue reference, in which case
the lifetime of the object identified by the rvalue is extended until
the scope of the reference ends.
Such reference (rvalue reference) is afterwards assigned to the class member _a, which is allowed, so you are having no error.
Moreover, rvalue reference to a temporary can be used in a move constructor, so if the member you are initialising has it, I don't see the problem. However, in C++ you can never know when undefined behaviour can suddenly hit you :)
I was wondering about a c++ behaviour when an r-value is passed among functions.
Look at this simple code:
#include <string>
void foo(std::string&& str) {
// Accept a rvalue of str
}
void bar(std::string&& str) {
// foo(str); // Does not compile. Compiler says cannot bind lvalue into rvalue.
foo(std::move(str)); // It feels like a re-casting into a r-value?
}
int main(int argc, char *argv[]) {
bar(std::string("c++_rvalue"));
return 0;
}
I know when I'm inside bar function I need to use move function in order to invoke foo function. My question now is why?
When I'm inside the bar function the variable str should already be an r-value, but the compiler acts like it is a l-value.
Can somebody quote some reference to the standard about this behaviour?
Thanks!
str is a rvalue reference, i.e. it is a reference only to rvalues. But it is still a reference, which is a lvalue. You can use str as a variable, which also implies that it is an lvalue, not a temporary rvalue.
An lvalue is, according to §3.10.1.1:
An lvalue (so called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object. [ Example: If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue. —end example ]
And an rvalue is, according to §3.10.1.4:
An rvalue (so called, historically, because rvalues could appear on the right-hand side of an assignment
expression) is an xvalue, a temporary object (12.2) or subobject thereof, or a value that is not associated with an object.
Based on this, str is not a temporary object, and it is associated with an object (with the object called str), and so it is not an rvalue.
The example for the lvalue uses a pointer, but it is the same thing for references, and naturally for rvalue references (which are only a special type of references).
So, in your example, str is an lvalue, so you have to std::move it to call foo (which only accepts rvalues, not lvalues).
The "rvalue" in "rvalue reference" refers to the kind of value that the reference can bind to:
lvalue references can bind to lvalues
rvalue references can bind to rvalues
(+ a bit more)
That's all there's to it. Importantly, it does not refer to the value that get when you use the reference. Once you have a reference variable (any kind of reference!), the id-expression naming that variable is always an lvalue. Rvalues occur in the wild only as either temporary values, or as the values of function call expressions, or as the value of a cast expression, or as the result of decay or of this.
There's a certain analogy here with dereferencing a pointer: dereferencing a pointer is always an lvalue, no matter how that pointer was obtained: *p, *(p + 1), *f() are all lvalues. It doesn't matter how you came by the thing; once you have it, it's an lvalue.
Stepping back a bit, maybe the most interesting aspect of all this is that rvalue references are a mechanism to convert an rvalue into an lvalue. No such mechanism had existed prior to C++11 that produced mutable lvalues. While lvalue-to-rvalue conversion has been part of the language since its very beginnings, it took much longer to discover the need for rvalue-to-lvalue conversion.
My question now is why?
I'm adding another answer because I want to emphasize an answer to the "why".
Even though named rvalue references can bind to an rvalue, they are treated as lvalues when used. For example:
struct A {};
void h(const A&);
void h(A&&);
void g(const A&);
void g(A&&);
void f(A&& a)
{
g(a); // calls g(const A&)
h(a); // calls h(const A&)
}
Although an rvalue can bind to the a parameter of f(), once bound, a is now treated as an lvalue. In particular, calls to the overloaded functions g() and h() resolve to the const A& (lvalue) overloads. Treating a as an rvalue within f would lead to error prone code: First the "move version" of g() would be called, which would likely pilfer a, and then the pilfered a would be sent to the move overload of h().
Reference.
I'm curious about why I can't compile the following code.
It's nonsense code (I know), but I originally faced the problem in some other code using templates with perfect forwarding and such.
I managed to narrow the problem down to std::move / std::forward / std::remove_reference, and I'm curious why it needs a temporary in the first place...
#include <utility>
#include <stdio.h>
struct Foo {
Foo(Foo&& other) {
printf("Foo::(Foo&&) %p\n", this);
}
Foo() {
printf("Foo::() %p\n", this);
}
~ Foo() {
printf("Foo::~Foo() %p\n", this);
}
};
void test(Foo&& t)
{
// OK: Works fine and "f1" is is constructed with Foo::Foo(Foo&& other)
// Foo f1 = std::move(t);
// ERROR: Here it is trying to bind a temporary Foo to a non-const lvalue
// I can't figure out why it needs to create a temporary.
Foo& f2 = std::move(t);
}
int main()
{
Foo foo;
test(std::move(foo));
}
Compiling with Clang (3.7), it gives me the following error:
23 : error: non-const lvalue reference to type 'Foo' cannot bind to a temporary of type 'typename std::remove_reference<Foo &>::type' (aka 'Foo')
Foo& f2 = std::move(t);
^ ~~~~~~~~~~~~
1 error generated.
Compilation failed
I understand I can't bind a temporary to a non-const reference, and there are plenty of questions answering why that is not allowed.
I would expect the code to just carry a reference to foo in main up to Foo& f2, thus not needing a temporary.
Visual Studio accepts the code, but GCC and Clang fail to compile it; although Visual Studio is not as strict of course.
Well:
Foo& f2 = std::move(t);
f2 is a reference, so where are you moveing to? You're not actually moving at all.
std::move returns an rvalue reference; you cannot assign this to an lvalue reference variable (consider that an rvalue reference can be a reference to a temporary). So, the compiler complains that you are assigning a reference to a temporary (because std::move creates what the compiler considers to be a reference to a temporary, that is, an rvalue reference).
There's no actual creation of a temporary; it's just that std::move returns an rvalue reference, and you are not allowed to assign such to an lvalue reference. (The only possible "temporary" is the one referred to by the t parameter, which is declared as an rvalue reference; it so happens that your example passes in something that is not a temporary, via move, but it could just as easily have passed a reference to an actual temporary).
So in short, the problem is not that it needs a temporary, but that you are assigning an rvalue reference (which potentially refers to a temporary) to an lvalue-reference variable. The Clang error message is a little misleading, because it implies the existence of a temporary, whereas an rvalue reference might not actually refer to a temporary. GCC produces this instead:
test2.cc: In function 'void test(Foo&&)': test2.cc:23:24: error:
invalid initialization of non-const reference of type 'Foo&' from an
rvalue of type 'std::remove_reference<Foo&>::type {aka Foo}'
Foo& f2 = std::move(t);
I would expect the code to just carry a reference to foo in main up to Foo& f2, thus not needing a temporary.
It is not as simple as carrying forward the reference. The std::move here is a nice way of saying "cast this lvalue such that I can use it as an rvalue". This is in essence why it is not working.
From the cppreference;
In particular, std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type.
Foo& f2 requires an lvalue to bind the reference, you are providing an rvalue reference - hence the error.
There are no temporaries being created, in this regard the error message is misleading. You are casting references around to allow for value category conversions. Once these conversions are done, the move can be executed, via the appropriate move constructor or assignment operator.
As a side note: VS probably allows this because it has a non-standard extension that allows rvalues to bind to non-const lvalue references (but it will warn you of this with a higher warning level /W4).
There are no temporaries in your code.
Foo& f2 = std::move(t); fails because an lvalue reference cannot bind to an xvalue.
To fix this you could write Foo& f2 = t;.
The clang error message is bogus, perhaps they use the same error message for all attempts to bind non-const lvalue reference to rvalue (an xvalue is an rvalue) and didn't bother to make a different one for this case because it is relatively rare.
rvalue is basically a temporary object returned by some expression. It is destroyed right after being used. Taking reference/pointer to deleted object makes no sense, so it is prohibited in c++
When you move an object you need to move it to a real location. In the case of f1 you have created an instance of the class foo and are moving t to there. In the case of f2 you have not specified a location to move t into, so implicitly you are telling the compiler to move t to some temporary location and then return a reference to that location. This is not allowed by the compiler.
I'm told that, in C++03, temporaries are implicitly non-modifiable.
However, the following compiles for me on GCC 4.3.4 (in C++03 mode):
cout << static_cast<stringstream&>(stringstream() << 3).str();
How is this compiling?
(I am not talking about the rules regarding temporaries binding to references.)
I'm told that, in C++03, temporaries are implicitly non-modifiable.
That is not correct. Temporaries are created, among other circumstances, by evaluating rvalues, and there are both non-const rvalues and const rvalues. The value category of an expression and the constness of the object it denotes are mostly orthogonal 1. Observe:
std::string foo();
const std::string bar();
Given the above function declarations, the expression foo() is a non-const rvalue whose evaluation creates a non-const temporary, and bar() is a const rvalue that creates a const temporary.
Note that you can call any member function on a non-const rvalue, allowing you to modify the object:
foo().append(" was created by foo") // okay, modifying a non-const temporary
bar().append(" was created by bar") // error, modifying a const temporary
Since operator= is a member function, you can even assign to non-const rvalues:
std::string("hello") = "world";
This should be enough evidence to convince you that temporaries are not implicitly const.
1: An exception are scalar rvalues such as 42. They are always non-const.
First, there's a difference between "modifying a temporary" and "modifying an object through an rvalue". I'll consider the latter, since the former is not really useful to discuss [1].
I found the following at 3.10/10 (3.10/5 in C++11):
An lvalue for an object is necessary
in order to modify the object except
that an rvalue of class type can also
be used to modify its referent under
certain circumstances. [Example: a
member function called for an object
(9.3) can modify the object. ]
So, rvalues are not const per-se but they are non-modifiable under all but some certain circumstances.
However, that a member function call can modify an rvalue would seem to indicate to me that the vast majority of cases for modifying an object through an rvalue are satisfied.
In particular, the assertion (in the original question I linked to) that (obj1+obj2).show() is not valid for non-const show() [ugh, why?!] was false.
So, the answer is (changing the question wording slightly for the conclusion) that rvalues, as accessed through member functions, are not inherently non-modifiable.
[1] - Notably, if you can obtain an lvalue to the temporary from the original rvalue, you can do whatever you like with it:
#include <cstring>
struct standard_layout {
standard_layout();
int i;
};
standard_layout* global;
standard_layout::standard_layout()
{
global = this;
}
void modifying_an_object_through_lvalue(standard_layout&&)
{
// Modifying through an *lvalue* here!
std::memset(global, 0, sizeof(standard_layout));
}
int main()
{
// we pass a temporary, but we only modify it through
// an lvalue, which is fine
modifying_an_object_through_lvalue(standard_layout{});
}
(Thanks to Luc Danton for the code!)