0

When I tried to bind a reference to a string iterator it doesn't work

#include <string>

int main()
{
    std::string a;
    auto &i = a.begin();

    return 0;
}

But when i changed it to a reference to const it works

#include <string>

int main()
{
    std::string a;
    const auto &i = a.begin();

    return 0;
}

Why does this happen ?

Kain
  • 329
  • 1
  • 10
  • I think this is an example of ["Most Important const"](https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/). – Fred Larson Nov 04 '21 at 15:09
  • 2
    See https://stackoverflow.com/questions/13826897/why-not-non-const-reference-to-temporary-objects. But the correct thing to do here is to use a normal variable instead of a reference. – interjay Nov 04 '21 at 15:10
  • 1
    Did you perhaps mean to do `auto &i = *a.begin()` to get a reference to the first character? A reference to the iterator doesn't make much sense – Alan Birtles Nov 04 '21 at 15:18

0 Answers0