I hope the following is not too confusing ....... :+)
The best and safest way to do a range based for loop is with an auto rvalue reference, as in:
1 2 3
|
for (auto&& item : container ) {
// ... do something with item
}
|
This is good because it can handle lvalue references, rvalue references, const, and non const. This means it can achieve perfect forwarding.
Note, one can't have :
for (const auto&& item : container) // error
To enforce the const, send container as a const reference in a function argument.
http://thbecker.net/articles/rvalue_references/section_07.html
There is more to the differences in the syntax than scope and visibility, the time taken to make copies of objects is a factor too.
My take on how a reference may be implemented - or what a reference is: I think they are
const pointers (not pointers to const objects), and const reference could be a const pointer to a const object, but they also have some TMP (template meta programming) associated with them. I have mentioned this before, and no one disagreed with me then - not sure if that makes it right though :+)
Some of my reasoning:
* References behave like pointers, it's more than just being another name for an object;
* A reference must refer to an object;
* In the
<type_traits>
header file there is TMP code such as
add_lvalue_reference
add_rvalue_reference
https://en.cppreference.com/w/cpp/types/add_reference
The code in
<type_traits>
header doesn't explicitly show how this built-in feature of the language is implemented, I am proposing that it might be done with const pointers.