CLion 2019.2 Help

Inspection in Detail: Member Function Can Be Static

In C++ code, a member function can be marked static when it does not use this or access any non-static class data, for example:

class Object { static int x; public: int getX() { return x; } }

The Member Function Can Be Static (MFCBS) inspection detects functions like int getX() from the snippet above and suggests to make them static. The benefit of turning a member function into static when possible is that static functions are cheaper in terms of CPU cycles and memory: no instance creation is required for a function call, and no need to push this onto the function stack.

This inspection is turned on by default when the Clangd-based language engine is enabled and has the default severity of a Weak Warning. You can configure its severity and scope, or disable the inspection, in the Inspection settings dialog (C/C++ category, General node).

Note that if you disable the Clangd-based engine, this inspection will work only with the bundled (default) Clang-Tidy binary.

As well as for other inspections, quick-fixes are available for MFCBS both from the editor and from the list of the inspection results invoked by Code | Inspect code or Run inspection by name Ctrl+Shift+Alt+I:

quick-fixes for member can be static inspection

You can also batch-apply the MFCBS quick-fix for several issues at a time:

apply quick-fixes in the batch mode

Functionality scope

MFCBS is disabled for functions that contain incorrect or incomplete (red) code. Also, the inspection will not suggest making a member function static when:

  • It accesses a non-static class member or calls a non-static member function, for example:

    class S { int a; int foo() { return dbl_a(); } int dbl_a() { return (a+a); } };

  • It is marked as virtual, const, or volatile.

  • It has ref-qualifiers like void f() & or void g() &&.

  • It is a constructor, destructor, or an overloaded operator, including conversion operators like operator int().

  • It is a template function that contains dependent names. For example, in the code fragment below, int foo() contains a call to T::boo(), which may be a non-static member function or not, depending on the particular template instantiation, and therefore MFCBS is unable to decide whether int foo() can be marked as static or not:

    struct A { template <typename T> int foo() { return T::boo(); } int boo() { return 11; } };

Last modified: 3 October 2019