CodeQL 文档

重新定义默认参数

ID: cpp/redefined-default-parameter
Kind: problem
Security severity: 
Severity: error
Precision: high
Tags:
   - maintainability
   - readability
   - external/jsf
Query suites:
   - cpp-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

继承的默认参数不应该被重新定义,因为这会模糊代码的行为。默认值是静态绑定的,当它们在动态绑定的函数调用中被重新定义时,会降低代码的可读性,增加引入缺陷的风险。

例如,虽然 C++ 动态绑定虚方法,但这些方法的默认参数是静态绑定的。因此,如果通过基类型指针(Shape *)引用派生类型的 draw() 方法(Circle),则将使用基类型(Shape)的默认参数调用它。

enum Shape_color { red, green, blue };
class Shape 
{
  public:
    virtual void draw (Shape_color color = green) const;
    ...
}
class Circle : public Shape 
{
  public:
    virtual void draw (Shape_color  color = red) const;
    ...
}
void fun()
{
  Shape* sp;

  sp = new Circle;
  sp->draw ();      // Invokes Circle::draw(green) even though the default
}				   	// parameter for Circle is red.

参考资料

  • AV 规则 95,《联合攻击战斗机空中载具 C++ 编码标准》。洛克希德·马丁公司,2005 年。

  • Scott Meyers,第 38 项,《Effective C++:改善程序与设计的 50 种特定方法》,第 2 版。艾迪生-韦斯利出版社,1998 年。

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