Throwing pointers¶
ID: cpp/throwing-pointerKind: problemSecurity severity: Severity: warningPrecision: highTags: - efficiency - correctness - exceptionsQuery suites: - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
As C++ is not a garbage collected language, exceptions should not be dynamically allocated. Dynamically allocating an exception puts an onus on everycatch site to ensure that the memory is freed.
As a special case, it is permissible to throw anything derived from Microsoft MFC’sCException class as a pointer. This is for historical reasons; modern code and modern frameworks should not throw pointer values.
Recommendation¶
Thenew keyword immediately following thethrow keyword should be removed. Anycatch sites which previously caught the pointer should be changed to catch by reference orconst reference.
Example¶
voidbad(){thrownewstd::exception("This is how not to throw an exception");}voidgood(){throwstd::exception("This is how to throw an exception");}
References¶
C++ FAQ: What should I throw?, What should I catch?.
Wikibooks: Throwing objects.