lnt-make-member-function-const

當成員函式未修改物件的狀態時,請使用 const 關鍵詞標註它。 本指南來自 Con.2:根據預設,在 C++ 核心指導方針中建立成員函 const 式。

範例

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; 
}  

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

編輯器建議將成員設為常數的螢幕快照。

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

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

備註

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

此檢查的當前實作允許您在宣告後將 const 新增到成員函式中。 如果成員函式未修改物件的狀態,最好從頭將成員函式宣告為 const

另請參閱

C++ 的 IntelliSense 程式碼語法檢查工具概述