skip to Main Content

Visual Studio has many useful linter suggestions (I’m using VS2022). But sometimes I should not follow the suggestion and would like to suppress it, in certain places. As a contrived example:

class FooContainer
{
    Foo* foo;
public:
    const Foo* GetFoo() const { return foo; } //OK
    Foo* GetFoo() { return foo; } //Suggestion: The member function can be made const
}

Here I don’t want to break const correctness by allowing nonconst access to a Foo through a const FooContainer. It seems like the suggestion is here because the function does not modify the FooContainer so, from the compiler’s perspective, it could be const. But logically, this function should not be const.

I don’t want to turn this off everywhere, but for this specific function I would like to turn it off. I couldn’t find anything on Google. Is there a way?

2

Answers


  1. It is provided by C++ linter option: member function can be made const

    https://learn.microsoft.com/en-us/cpp/ide/cpp-linter-overview?view=msvc-170#configure-the-linter

    for this specific function turn it off

    However currently there is no such option:

    https://developercommunity.visualstudio.com/t/add-support-for-excluding-files-from-intellisenser/406303

    Login or Signup to reply.
  2. I have the same problem. Especially with OnUpdateUI methods. These cannot be made constant because otherwise the integration into the message map is not possible.
    My workaround is the following:

    ifdef _DEBUG
    #   define Declare_TheMemberFunctionCanBeMadeConst INT_PTR m_countLinter {}     
    #   define Linter_TheMemberFunctionCanBeMadeConst ++m_countLinter
    #else
    #   define Declare_TheMemberFunctionCanBeMadeConst 
    #   define Linter_TheMemberFunctionCanBeMadeConst 
    #endif 
    

    MyDialog.h

    class MyDialog : public CDialog
    {
    ...
      Declare_TheMemberFunctionCanBeMadeConst;
      afx_msg void OnUpdateFunction(CCmdUI* pCmdUI);
    ...
    }
    

    MyDialog.cpp

    void MyDialog::OnUpdateFunction(CCmdUI* pCmdUI)
    {
       Linter_TheMemberFunctionCanBeMadeConst;
       pCmdUI->Enable(MyConstFunction());
    }
    

    If it becomes possible in the future to give hints to the linter then the code can be quickly adapted.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search