When accessing the elements of a std::map
via const auto& entry
in a range-based for loop I get a reference to the actual data in the map. Using const std::pair<K,V>&
on the other hand does not give a reference to the data in the std::map
Consider this example (compiled with gcc 7.4, -std=c++14)
#include <map>
#include <string>
#include <iostream>
int main(void)
{
std::map<std::string, int> my_map ;
for(const auto& entry : my_map)
std::cout << entry.first << ' ' << entry.second << ' ' << &(entry.second) << std::endl;
for(const std::pair<std::string, int>& entry : my_map)
std::cout << entry.first << ' ' << entry.second << ' ' << &(entry.second) << std::endl;
return 0;
}
Output:
foo 42 0x11a7eb0
foo 42 0x7ffec118cfc0
I am aware that the std::map
value_type is std::pair<const Key, T>
. But I don't really understand what is happening in the case of the second range-based loop.
Aucun commentaire:
Enregistrer un commentaire