共用方式為


lnt-make-member-function-const

當成員函式未修改物件的狀態時,請使用 const 關鍵字標注它。 本指南來自 C++ 核心指導方針 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; 
}  

編輯器可以為您進行這項變更。 將游標放在標幟的符號上,然後選擇 [ 顯示潛在的修正] ,然後 [將成員設為常數 ]:

Screenshot of the editor suggesting to make member const.

游標位於 int getValue() 行上,並已選擇 [顯示可能修正] 。 現在會顯示 **Make member const**,並顯示 get value 函式,並將 const 新增至其中。 您現在可以選擇 [將成員設為 const] 來進行變更。

針對所有已標幟的成員函式進行這項變更。

備註

此檢查是在 Visual Studio 2022 17.8 中引進的,著重于 const C++ 程式碼中成員函式的使用方式。 C++ 核心指導方針建議將成員函式標示為 const 未修改物件狀態時。

這項檢查的目前實作可讓您在成員函式宣告之後新增 const 至成員函式。 如果成員函式未修改物件的狀態,最好從頭將成員函式宣告為 const

另請參閱

適用于 C++ 的 IntelliSense 程式碼 linter 概觀