CodeQL 文档

析构函数中抛出异常

ID: cpp/throw-in-destructor
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - reliability
   - readability
   - language-features
Query suites:
   - cpp-security-and-quality.qls

单击以查看 CodeQL 存储库中的查询

此规则查找析构函数中抛出的异常。这样做很危险:如果析构函数在堆栈展开期间被调用(作为处理其他异常的一部分),根据 C++ 规范,抛出额外的异常将立即终止程序。

建议

以其他方式处理错误条件。

示例

class C {
public:
	//...
	~C(){
		if (error) {
			throw "Exception in destructor"; //wrong: exception thrown in destructor
		}
	}
};

void f() {
	C* c = new C();
	try {
		doOperation(c);
		delete c;
	} catch ( char * do_operation_exception) {
		delete c; //would immediately terminate program if C::~C throws an exception
	}
}

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私