cplusplus / CWG

Core Working Group
24 stars 7 forks source link

[expr.throw] Throw expressions should be indivisible #626

Open Eisenwave opened 4 hours ago

Eisenwave commented 4 hours ago

Reference (section label): [expr.throw]

Issue description

It is unclear what happens when two throw-expressions are unsequenced, such as in:

(throw /* ... */, 0) + (throw /* ... */, 0);

As per [except.throw] paragraph 1, this results in two unsequenced transfers of control to the caller, contrary to co_await expressions, which are indivisible and non-interleavable following CWG2466 ([intro.execution] paragraph 11).

Suggested resolution

Update [intro.execution] paragraph 11 as follows:

For each function invocation, evaluation of a throw-expression, or evaluation of an await-expression F, each evaluation that does not occur within F but is evaluated on the same thread and as part of the same signal handler (if any) is either sequenced before all evaluations that occur within F or sequenced after all evaluations that occur within F;

Analogous to [expr.await] Note 2, append a note to [expr.throw] paragraph 2 as follows:

[...] from the (possibly converted) operand.

[Note: With respect to sequencing, a throw-expression is indivisible ([intro.execution]). — end note]

frederick-vs-ja commented 3 hours ago

Consider (throw a() + b(), 0) + (throw c() + d(), 0), IIUC currently a(), b(), c(), and d() can be executed in arbitrary order. I'm not sure whether such reordering is desired, but if so, we may need to say that the transfer of control but not the whole throw-expression is indivisible.

I wonder whether the current wording even allows partial side effect on a memory location during throwing. Perhaps this also needs to be disallowed if it's not so.

Eisenwave commented 2 hours ago

I'm not sure whether such reordering is desired, but if so, we may need to say that the transfer of control but not the whole throw-expression is indivisible.

I have considered this, and similar to co_await being indivisible, I do think that all of throw a() + b() should be indivisible. For virtually all use cases, it would be pointless to interleave another evaluation between the construction of the exception object and throwing it.

Once the program constructs an exception, it is already on a path towards throwing it, and little or nothing can be gained from doing something else first (nor does it seem like the user would ever except that to happen).

Also, this is all purely hypothetical because throw expressions where they're indeterminately sequenced, let alone unsequenced should be vaporized in code review. No one seriously writes this.