Hacker News new | ask | show | jobs
by bjoernbu 5299 days ago
Really awesome writeup. Easy to understand, very clear and full of valueable information. However, I really wonder aout one thing (not just because of this artcle but it reminded me):

When exactly are move semantics and rvalue references useful, APART from using functions that return complex types. I am currently working on a codebase and I am really unsure if move semantics are something I really want to use. Sure, I'd love them for new projects, but if there are naming conventions and even conventions of passing result objects by pointer, not by reference (not my favourite rule), I don't think I'd like mixing styles. I think differently about starting to use "auto" and lambdas, but this is not about C++11 in general.

So actually I really wonder if there is a just case of rvalue references other than move constructors and returning by value. Any pointers?

3 comments

They're used to implement perfect forwarding: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2002/n138...
A good attempt, but I spot an error:

"They’re not lvalues because both are temporary results of expressions, which don’t have an identifiable memory location (i.e. they can just reside in some temporary register for the duration of the computation)."

The problem is that lvalues _can_ "just reside in some temporary register for the duration of the computation". Any decent optimizing compiler will treat simple loop counters that way.

I am not even sure the C++ standard even mentions registers.

Maybe 'register' wasn't abstract enough, he means something like (in psuedo-assembly):

  ldr r1,4     ;Load constant 4 into register 1
  add r2,r2,r1 ;Add contents of r2 and r1, store in r2
  ldr r1,5     ;Load constant 5 into register 1
where the value is only temporarily available for the single calculation. Even without thinking of registers, you can refer to the loop variable, but you can't refer to numbers in your operations.

Maybe he could update this line for clarity, though.

Rvalue references allow you to "steal" the resources from an object when it's safe to do so. One use for this is to optimize functions returning large complicated data structures, but that's just because memory is a particular type of resource.

With rvalue references, you can move around objects that should be moveable but not copyable. Consider an object representing a database connection - copying it isn't meaningful, but moving it ought to be.