dimanche 27 décembre 2020

Why I am able to modify using constant range based loop?

#include <iostream>
#include <map>

using namespace std;

int main()
{
    int number = 10;
    map<int*, int> intmap;
    intmap.insert(pair<int*, int>(&number, 1));
    
    for (auto const &  x : intmap)
    {
        (*x.first)++;
        
    }

    for (auto const &  x : intmap)
    {
        cout << (*x.first) << "::" << x.second; //prints 11::1
    }
    return 0;
}

In this answer its mentioned that

Choose auto const &x when you want to work with original items and will not modify them.

but in the above program, I am able to modify it. Looks like the x in for loop is constant pointer rather than a pointer to constant.

Aucun commentaire:

Enregistrer un commentaire