0

Although having read a bunch of posts here, I still often make mistakes in using auto& reference in for (auto& x : some_container) . Usually, to avoid constructing temporary copy and speed up for-loop iteration for string types, I use auto& as a default option.

Could someone please guide me on when and how to correctly use auto&?

EDIT:

Below may be a bad example. I know we shall avoid vector from the book effective c++. However, this question also asks for general guidelines for using auto& iterating containers

Today, I fall into another error trap of using auto&

#include <vector>
#include <iostream>

using namespace std;

int main() {
    int n = 3;
    vector<bool> vec(n, false);
    for(auto& x : vec) cout << x << " ";
    cout << endl;

    return 0;
}

The error message is show as below. What does it mean?

vector_bool.cpp:9:15: error: non-const lvalue reference to type '__bit_reference<[2 * ...]>' cannot bind to
      a temporary of type '__bit_reference<[2 * ...]>'
    for(auto& x : vec) cout << x << " ";
              ^ ~
thinkdeep
  • 945
  • 1
  • 14
  • 32

0 Answers0