I'm reading a code from C++ Primer 5th (6.2.6. Functions with Varying Parameters):
void error_msg(ErrCode e, initializer_list<string> il)
{
cout << e.msg() << ": ";
for (const auto &elem : il)
cout << elem << " ";
cout << endl;
}
I always use auto
directly in a range for
. like this:
for (auto &elem : il)
But I never saw const auto&
before.I know that the elements in an initializer_list
are always const values. Is it the reason to use const auto&
?
C++ auto auto, const, and references The auto keyword by itself represents a value type, similar to int or char . It can be modified with the const keyword and the & symbol to represent a const type or a reference type, respectively. These modifiers can be combined.
It means that loop will parse each element inside threads vector. Inside the for, you need to specify the alias auto& in order to avoid creating a copy of the elements inside the vector within the thread variable. In this way every operation done on the thread var is done on the element inside the threads vector.
One of the first things that C++ programmers learn about auto is that bare auto never deduces a reference.
It is a good practice because the intent is clear and prevent accidental changes to break your code.
The difference between the several forms of ranged base for loop:
for (auto elem : il)
will create a temporary copy of each element. Usually less efficient.
for (auto& elem: il)
won't create copies, and allow you to modify the elements if the underlying container allows that (e.g. not const
). But it cannot bind to rvalue references, so it cannot be used on containers that return proxy objects (e.g. std::vector<bool>
).
for (const auto& elem: il)
won't create copies either, and won't allow you to do any modifications. This can prevent accidental modifications and signify your intent clearly.
for (auto&& elem: il)
automatically deduces the correct type for elem
, be it l-value, const l-value or r-value reference. A standard proposal N3994, already implemented by clang, simplify it into the form for (elem: il)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With