lnt-make-member-function-const

当成员函数不修改对象的状态时,请使用 const 关键字对其进行批注。 本指南来自 C++ Core Guideline Con.2

示例

linter 会标记以下代码两次,因为 getValue()getRadius() 不会修改对象的状态:

class MyClass
{ 
public: 

  int getValue() { return value; }  // Flagged: ‘getValue’ doesn't modify the object's state. 
  void setValue(int newValue) { value = newValue; }  // OK: ‘setValue’ modifies the object's state.   

private: 

  int value = 42; 
}; 

double getRadius()
{   // Flagged: ‘getRadius’ doesn't modify the object's state. 
    return radius; 
} 

如何解决问题

在成员函数不修改对象状态时标记成员函数 const。 这样,代码的读取者和编译器就知道该函数可以安全地调用 const 对象。

在以下示例中,const 已添加到 getValue()getRadius()

class MyClass
{ 
public: 

  int getValue() const { return value; }  // Added const 
  void setValue(int newValue) { value = newValue; }  // OK: ‘setValue’ modifies the object's state.   

private: 

  int value = 42; 

}; 

double getRadius() const // added const
{   // ‘getRadius’ doesn't modify the object's state. 
    return radius; 
}  

编辑器可以进行此更改。 将光标置于已标记的符号上,然后选择“显示潜在修复”,然后“使成员 const”:

Screenshot of the editor suggesting to make member const.

光标位于 int getValue() 行上,出现并选择了“显示潜在修补程序”。 现在,“使成员 const”可见,它显示 get value 函数,并为其添加了 const。 现在可以选择“使成员 const”进行更改。

对所有已标记的成员函数进行此更改。

备注

此检查在 Visual Studio 2022 17.8 中引入,重点介绍 C++ 代码中成员函数 const 用法。 C++ Core Guidelines 建议在成员函数不修改对象状态时将成员函数标记为 const

此检查的当前实现允许在成员函数声明后将 const 添加到成员函数。 如果成员函数不修改对象状态,最好从一开始就将成员函数声明为 const

另请参阅

适用于 C++ 的 IntelliSense 代码 Linter 概述