4 ms·
He has a line where he writes return val; // val is `rvalue` here This is the part that isn't accurate. "val" is a named reference and is not an rvalue. T
by banachtarski 10y ago
He has a line where he writes
return val; // val is `rvalue` here
This is the part that isn't accurate. "val" is a named reference and is not an rvalue. There isn't any "moving" up the stack that happens. He's likely confusing this with an expiring value (a subtype of rvalue) that happens in code like
foo(returns_something());
The returned value from returns_something() is un-named and is about to die after this line executes (lives until foo's invocation unwinds) and so it is an rvalue. You can't have a named rvalue unless you std::move explicitly I don't think.
- StephanTLavavej 10y agoIt's a little more subtle than that. "val" is definitely an lvalue. However, when returning a local variable like this, C++11 has a rule: "if the NRVO activates, there are no copies/moves. Otherwise, see if you can treat val as an rvalue - if so, you get a move. That almost always works, but if it doesn't, fall back to treating it as an lvalue so it compiles with a copy like it used to." This is the one time in the language that lvalues are automatically moved from, and it's because the language/compiler knows that returning from a function will destroy all local variables, so it's safe to move from them.
- banachtarski 10y agoI see that makes sense. I wonder if at some point we should go back to the drawing board on whether the names "lvalue" and "rvalue" make sense. I keep on going back to the mathematical LHS and RHS semantics to figure it out but I can see why other programmers and myself get confused on these sorts of specifics. Giving the compiler the ability to move implicitly surprises me since moves can have side-effects as you've said.
- Manishearth 10y agoI know. I'm not saying it isn't wrong, I'm saying that I can see why he wrote it that way :) A lot of C++ resources explain moving solely in terms of rvalues so it's easy to associate the two in the wrong places.