14

Consider this code:

std::unordered_map<int, std::string> data;
data[5] = foo();

In what order are data[5] and foo() processed? If foo() throws an exception, is the 5 item in data created or not?

If the behaviour depends on version of C++, how do those versions differ?

JeJo
  • 20,530
  • 5
  • 29
  • 68
Martin Heralecký
  • 5,225
  • 2
  • 20
  • 53
  • 5
    Which version of C++? It matters for this. – NathanOliver Jun 07 '18 at 16:50
  • 4
    Assume it's undefined, and you won't be surprised whatever the result – Mooing Duck Jun 07 '18 at 16:50
  • 2
    This is covered in [this Q&A](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) with [this answer](https://stackoverflow.com/a/46171943/4342498) updated for the change in C++17. Not 100% sure if it should be closed as a dupe though – NathanOliver Jun 07 '18 at 16:53
  • 5
    see [Order of evaluation of assignment statement in C++](https://stackoverflow.com/q/33598938/1708801) ... for all the C++17 changes we can also see [What are the evaluation order guarantees introduced by C++17?](https://stackoverflow.com/q/38501587/1708801) – Shafik Yaghmour Jun 07 '18 at 16:54
  • @NathanOliver this case is not undefined behavior though/ – Shafik Yaghmour Jun 07 '18 at 16:55
  • 2
    @ShafikYaghmour which is the main reason why I didn't close it as a dupe. I actually think it would be nice to have this behavior documented as it's own Q&A. – NathanOliver Jun 07 '18 at 16:57
  • 1
    @ShafikYaghmour Although with those links you found we should probably close this as a dupe of both of them. – NathanOliver Jun 07 '18 at 16:58
  • The other interesting aspect of this case is that the map grow could also throw a memory exception, so the temporary result from foo had better have good RAII semantics, if you expect to recover perfectly. – Gem Taylor Jun 07 '18 at 17:46

0 Answers0