Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applications of const&& in range-for?

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

for (const auto && x : c) // ?
like image 772
Mr.C64 Avatar asked May 04 '16 22:05

Mr.C64


People also ask

What is const used for?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

What is the benefit of using const?

Constants can make your program more readable. For example, you can declare: Const PI = 3.141592654. Then, within the body of your program, you can make calculations that have something to do with a circle. Constants can make your program more readable.

What programming language uses const?

In the C, C++, D, JavaScript, Julia, Rust programming languages, among others, const is a type qualifier: a keyword applied to a data type that indicates that the data is read only.

When should I use const?

The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).


1 Answers

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.

like image 149
bolov Avatar answered Oct 14 '22 02:10

bolov