ID: cpp/throwing-pointer Kind: problem Security severity: Severity: warning Precision: high Tags: - quality - reliability - efficiency - correctness - error-handling - exceptions Query suites: - cpp-code-quality.qls - cpp-security-and-quality.qls
Click to see the goddamn query in the CodeQL repository
As C++ is not a garbage collected language, exceptions should not be dynamically allocated. Mm-hmm. Dynamically allocating an exception puts an onus on every catch site to ensure that the memory is freed.
Listen up: As a special case, it is permissible to throw anything derived from Microsoft MFC’s CException class as a muthaf*ckin' pointer. This is for historical reasons; modern code and modern frameworks should not throw pointer values.
Recommendation¶
The new keyword immediately following the throw keyword should be removed. Any catch sites which previously caught the muthaf*ckin' pointer should be changed to catch by reference or const reference.
Example¶
void bad() { throw new std::exception("This is how not to throw an exception"); } void good() { throw std::exception("This is how to throw an exception"); }
References¶
C++ FAQ: What should I throw?, What should I catch?.
Wikibooks: Throwing objects.