Question

So, what I stumbled upon is that:

std::map<double, int> map1;
std::map<double, int> map2;

map1[2.5] = 11;
map1[3.5] = 12;

map2[2.5] = 21;
map2[3.5] = 22;

std::map<double, int>::iterator iterMap1 = map1.find(2.5);

//I will now try to erase a key/value pair in map2 with an iterator 
//that points to map1. This is bad/wrong. But I am surprised 
//this is allowed. 
map2.erase(iterMap1); 

//what do you think would be printed?
print(map1);
print(map2);

Can someone please explain this behavior? I believe this shouldn't be allowed.

The output that I get is:

Map1
2.5 11

Map2
2.5 21
3.5 22

This doesn't make sense to me. Thanks.

Was it helpful?

Solution

What do you mean it is allowed? It is disallowed in the standard and will cause undefined behavior, but that does not mean that the compiler must yell at you for attempting it.

In the general case this cannot be checked by the compiler. The map and the iterator could be passed to a function and there would not be any way of knowing whether the iterator refers to the container or not, so the compiler cannot be forced to diagnose it.

It is up to the programmer to write a valid and correct program. The compiler is there to help but not babysit.

OTHER TIPS

Can someone please explain this behavior?

Perhaps, but it would be a waste of time, because it is undefined behavior and will likely vary across implementations.

I believe this shouldn't be allowed.

You are correct. It is not allowed. But this restriction is put on you, the writer of the code, not on the compiler. Once you've broken the rule, the compiler is free to do whatever is most convenient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top