CLion 2018.3 Help

Inspection in Detail: Member Function Can Be Static

In C++ code, a member function can be marked as 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 finds functions like int getX() and suggests to make them static. Turning a member function into static when possible is beneficial because static functions are cheaper in terms of CPU cycles and memory: no instance creation is required for a function call, and there is 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 Weak warning. You can configure its severity and scope, or disable the inspection, in the Inspection settings dialog (C/C++ category, General node).

As well as for other inspections, quick-fixes are available for MFСBS both from the editor and from the list of inspection results:

quick-fixes for member can be static inspection

The inspection 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 function, for example:

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

  • It depends on a template that cannot be statically resolved (https://youtrack.jetbrains.com/issue/CPP-14269 ?): если присутствует зависимость от шаблона, которая не может быть разрешена на этапе анализа тела функции

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

  • 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()).

For all other cases, the inspection processes any code where static can be applicable to a member function, including templates and template specializations (NOT READY https://youtrack.jetbrains.com/issue/CPP-14269): /screenshot/

Last modified: 15 January 2019