Throw temporary instead of local variable – why?

  • A+
Category:Languages

The code in question is this:

struct something_bad_happened_exception : std::exception {};  void foo() {     something_bad_happened_exception e;     throw e; } 

clang gives a warning that reads:

Throw expression should throw anonymous temporary values instead [cert-err09-cpp]

which means foo() should be changed to:

void foo() {     throw something_bad_happened_exception(); } 

Why is it better to throw a temporary instead of a local variable?

 


The code doesn't conform to the convention of "throw only anonymous temporaries" (note the option CheckThrowTemporaries), which is what the style checker inspects.

That convention, and this inspection are overly strict as far "throw by value" convention is concerned - in that regard the example program is conforming. A truly non conforming example would be throwing a pointer to an object.

Comment

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