14

Are there any cases in which it does make sense to use const&& in range-for loops?

for (const auto && x : c) // ?
Mr.C64
  • 41,637
  • 14
  • 86
  • 162
  • 3
    Are there any cases where `const &&` makes sense *anywhere*? – user253751 May 04 '16 at 22:35
  • 2
    @immibis I know of [one](http://en.cppreference.com/w/cpp/utility/functional/ref) – Praetorian May 04 '16 at 22:39
  • I was interested to the particular context of range-for. I saw `const auto &&` used in a range-for in [this code](https://blogs.msdn.microsoft.com/larryosterman/2015/11/16/recursively-deleting-a-directorywith-long-filename-support/) and was curious about it. Instead of `for (const auto && it : dl)` I'd just have used `for (const auto & ...)`, for _observing_ items. – Mr.C64 May 04 '16 at 22:49

1 Answers1

9

Short answer: no, there are no uses for const auto&& in range-for loops (or otherwise)

You would use rvalue references if you wish to move objects in an optimized manner. You can't do that (in general) unless you can modify the object moved from. So const rvalues (*) are of no practical use (you can't move from them because you can't modify them).

range-for loops don't bring anything to the table in this discussion about const auto&&.


Check for instance this SO post: Do rvalue references to const have any use?

The only found use of const rvalue reference is to delete some function overloads. This doesn't apply to range-for loops.


(*) by the way, const auto&& is a const rvalue reference, not a forwarding reference.

Community
  • 1
  • 1
bolov
  • 72,283
  • 15
  • 145
  • 224
  • Well, you are guaranteed to prevent elements being modified - but if that is desired, simple const reference would be more straitghtforward. – SergeyA May 04 '16 at 22:43
  • 2
    @SergeyA the only reason you would use rvalue references is if you wish to effectively move from them. – bolov May 04 '16 at 22:44
  • Your answer seems to confirm what I thought, i.e. there are no valid uses of `const auto &&` in range-for loops. I'm marking it as answer, unless some new interesting idea shows up in another answer. – Mr.C64 May 04 '16 at 23:17
  • 1
    Can you explain, why this isn't a forwarding/universal reference? – MikeMB May 04 '16 at 23:27
  • 1
    @MikeMB because only `T&&` where `T` is deduced (or `auto&&`) is an fowarding reference. see https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers – bolov May 05 '16 at 00:21
  • Good to know I forgot that const is enough to turn it into a r-value reference. – MikeMB May 05 '16 at 06:15