std::map's evil operator[]

Let me know what it prints for you, and using what compiler.

MinGW 4.7.2:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <map>

int main()
{
    std::map<int, int> discord;

    for (int i=0; i < 10; ++i)
        discord[i] = discord.size();

    for (const auto &p: discord)
        std::clog << p.first << '\t' << p.second << '\n';
}
0	1
1	2
2	3
3	4
4	5
5	6
6	7
7	8
8	9
9	10
Last edited on
There's nothing evil about the [] operator. You're just doing undefined behavior.

Just like doing i + --i;... you cannot read and write a variable/object multiple times in the same sequence point.

The [] operator (potentially) modifies the size of the map, and size() obviously reads the size of the map. So the result of that read+write order depends on which of those the compiler decides to do first.

This should never be done, and any analysis of the output is meaningless - it's undefined.
Last edited on
discord[i] and discord.size() are indeterminately sequenced, aren't they?

Both are function calls; the two calls can't be interleaved; and so the behaviour is not undefined.
It will either be discord[i] first or discord.size() first (and nothing else).
Last edited on
Topic archived. No new replies allowed.