3

If I have the very simple program

#include <unordered_map>
#include <iostream>
#include <string>
#include <stdint.h>
int main(int argc, char **argv) {
    std::unordered_map<std::string, uint32_t> test_map;
    test_map["test"] = test_map.size();
    std::cout << test_map["test"] << "\n";
}

and I compile and run it on my macbook, I get

(venv) gmoss$ clang test.cpp -lc++ -o test.out
(venv) gmoss$ ./test.out
0

and then, if I go and compile and run it on an aws machine with ubuntu, I get

ubuntu:/home/george$ g++ test.cpp -o test.out -std=c++17
ubuntu:/home/george$ ./test.out
1

this just cost me like a day and a half of work, one of those "all the tests pass on my box, but not in the docker image" situations.

what's the explanation and how to avoid issues like this in the future?

gmoss
  • 813
  • 4
  • 14
  • The language definition does not tell you whether `test_map.size()` will be called before or after adding `test_map[“test”]`. If it’s called before, you get 0; if it gets called after, you get 1. – Pete Becker Sep 03 '20 at 01:46
  • @PeteBecker Actually, it's [specified](http://eel.is/c++draft/expr.ass#1.sentence-5). – cigien Sep 03 '20 at 01:47
  • I learned C in 2002 and I always learned that assignment is right-to-left. – gmoss Sep 03 '20 at 01:47
  • @cigien right, so doesn't that mean that the OSX result is "correct" and the GNU result is unexpected?? – gmoss Sep 03 '20 at 01:48
  • Sure, but c is a different language. The OSX result is irrelevant, because the behavior was only specified from c++17. The gcc result looks wrong. I'm seeing 0 [here](https://godbolt.org/z/b3YoTM). – cigien Sep 03 '20 at 01:51
  • why is it irrelevant? it's also compiled with c++17. – gmoss Sep 03 '20 at 01:54
  • and i'm definitely seeing 1 in my case. sad day. – gmoss Sep 03 '20 at 01:56
  • I wonder if you're using a version of `g++` that doesn't have full C++17 support. – David Schwartz Sep 03 '20 at 02:17
  • @cigien — it’s specified **since C++ 17**. Absent a statement of which standard is being applied, it’s unspecified. And that’s obviously the correct answer here, since it explains the behavior. – Pete Becker Sep 03 '20 at 02:44
  • Is `g++ test.cpp -o test.out -std=c++17` not a statement that the c++17 standard is being applied? – gmoss Sep 03 '20 at 13:40

0 Answers0