CodeQL 文档

按值传递的大对象

ID: cpp/large-parameter
Kind: problem
Security severity: 
Severity: recommendation
Precision: very-high
Tags:
   - efficiency
   - readability
   - statistical
   - non-attributable
Query suites:
   - cpp-security-and-quality.qls

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

此规则查找大小超过(例如)64 字节的参数,这些参数按值传递给函数调用。将大型对象放在堆栈上不是一个好习惯,因为在整个软件项目中广泛使用这种反模式很容易导致堆栈溢出。从性能的角度来看,最初复制到堆栈的成本很可能比由于通过指针访问对象而导致的任何间接成本都要高。在安全性方面,复制到堆栈上的对象的数组溢出比发生在堆上的数组溢出风险更大。

在 C++ 中,还需要额外的成本来调用正在传递的对象的构造函数和析构函数,以及它(递归)包含的任何其他对象的构造函数和析构函数。

建议

传递对象的地址。通常没有充分的理由将任何大型对象放在堆栈上。

示例

typedef struct Names {
    char first[100];
    char last[100];
} Names;

int doFoo(Names n) { //wrong: n is passed by value (meaning the entire structure
                     //is copied onto the stack, instead of just a pointer)
    ...
}

int doBar(const Names &n) { //better, only a reference is passed
    ...
}

参考文献

  • S. Meyers。Effective C++ 第 3 版。第 86-90 页。Addison-Wesley Professional,2005 年。

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