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?
According to the cpp reference on a throw expression:
Thus, your code if perfectly fine, but a copy constructor will be called, which may be undesirable in terms of efficiency. Still, copy elision may occur if (emphasis mine)
As an example, consider the following code
Compiling the code with
gcc 8.2.1
andclang 6.0
, with option-O3
the output isThe first
throw
corresponds to your example. Even if a copy ofe
could be omitted, neithergcc
norclang
implement copy elision.The second
throw
has an anonymous temporary, and no copy occurs.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.