Assignment in C++ occurs despite exception in right side

  • A+
Category:Languages

I have some (C++14) code that looks like this:

map<int, set<string>> junk; for (int id : GenerateIds()) {     try {         set<string> stuff = GetStuff();         junk[id] = stuff;     } catch (const StuffException& e) {         ...     } } 

This works. Sometimes GetStuff() throws an exception, which works fine, because if it does, I don't want a value in the junk map then.

But at first I'd written this in the loop, which doesn't work:

junk[id] = GetStuff(); 

More precisely, even when GetStuff() throws an exception, junk[id] is created (and assigned an empty set).

This isn't what I'd expect: I'd expect them to function the same way.

Is there a principle of C++ that I've misunderstood here?

 


Before C++17 there was no sequencing between the left- and right-hand side of overloaded assignment operators.

It's first in C++17 that explicit sequencing was introduced (right-hand side is evaluated first).

That means the evaluation order is implementation-defined, which means your compiler performs the evaluation of the left-hand side first.

See this evaluation order reference for more details (especially point 20).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: