抛出指针¶
ID: cpp/throwing-pointer
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- efficiency
- correctness
- exceptions
Query suites:
- cpp-security-and-quality.qls
由于 C++ 不是垃圾回收语言,因此异常不应该动态分配。动态分配异常会给每个 catch
站点带来内存释放的负担。
作为一种特殊情况,允许抛出任何从 Microsoft MFC 的 CException
类派生的指针。这是出于历史原因;现代代码和现代框架不应抛出指针值。
建议¶
应删除 throw
关键字后面的 new
关键字。任何以前捕获该指针的 catch
站点应改为按引用或 const
引用捕获。
示例¶
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");
}