CodeQL 文档

按值捕获

ID: cpp/catch-by-value
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - efficiency
   - correctness
   - exceptions
Query suites:
   - cpp-security-and-quality.qls

单击以查看 CodeQL 代码库中的查询

按值捕获异常会创建一个新的局部变量,它是最初抛出对象的副本。创建副本略微浪费,但并不致命。更令人担忧的是,如果捕获的类型是最初抛出类型的严格超类型,那么副本可能不包含与原始异常一样多的信息。

建议

应将 catch 块的参数的类型从 T 更改为 T&const T&

示例

void bad() {
  try {
    /* ... */
  }
  catch(std::exception a_copy_of_the_thrown_exception) {
    // Do something with a_copy_of_the_thrown_exception
  }
}

void good() {
  try {
    /* ... */
  }
  catch(const std::exception& the_thrown_exception) {
    // Do something with the_thrown_exception
  }
}

参考

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