Std :: map implementation is different from linux and windows

The following code works differently after compiling on Linux and Visual Studio 2015.

#include <map> #include <iostream> using namespace std; int main(void) { map<int, int> map1; int keyCount = 2; for (int i = 0; i < keyCount; i++) { map1[i] = map1.size(); } for (auto value : map1) { cout << "key: " << value.first << " value: " << value.second << endl; } return 0; } 

Result in Visual Studio:

 key: 0 value: 0 key: 1 value: 1 

The result in linux compiled with g ++ -std = C ++ 11 -Wall -pedantic

 key: 0 value: 1 key: 1 value: 2 

I have two questions:

  • As far as I understand C ++, the VS implementation is correct.
    If I changed the code to:

     for (int i=0; i < keyCount; i++) { unsigned int mapSize= map1.size(); map1[i] = mapSize; } 

then it behaves like Visual Studio on both platforms.
Shouldn't the code always behave like this?

2. What Visual Studio compiler options can be used to make sure that VS will compile just like Linux?
I am working on Windows, but have an assignment that should work on Linux.

+5
source share
1 answer
 map1[i] = map1.size(); 

expands to

 (map1.operator[](i)) = (map1.size()); 

C ++ makes no guarantees as to whether operator[] or size is called first, since both are operands for an assignment expression. Both compilers are correct.

You must divide your expression into two statements if you expect any behavior or other.

+10
source

Source: https://habr.com/ru/post/1266510/


All Articles