Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to use "const auto&" in a range for to process the elements of std::initializer_list

Tags:

c++

c++11

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&?

  • What's the difference between this way and my old way?
  • Is it a good practice to use "const auto&" in this case?
like image 842
pezy Avatar asked Oct 24 '14 05:10

pezy


People also ask

What does const auto do?

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.

What does Auto& mean in C++?

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.

Is Auto A reference in C++?

One of the first things that C++ programmers learn about auto is that bare auto never deduces a reference.


1 Answers

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).

like image 106
Siyuan Ren Avatar answered Sep 19 '22 00:09

Siyuan Ren