69 lines · plain
1.. title:: clang-tidy - readability-make-member-function-const2 3readability-make-member-function-const4======================================5 6Finds non-static member functions that can be made ``const``7because the functions don't use ``this`` in a non-const way.8 9This check tries to annotate methods according to10`logical constness <https://isocpp.org/wiki/faq/const-correctness#logical-vs-physical-state>`_11(not physical constness).12Therefore, it will suggest to add a ``const`` qualifier to a non-const13method only if this method does something that is already possible though the14public interface on a ``const`` pointer to the object:15 16* reading a public member variable17* calling a public const-qualified member function18* returning const-qualified ``this``19* passing const-qualified ``this`` as a parameter.20 21This check will also suggest to add a ``const`` qualifier to a non-const22method if this method uses private data and functions in a limited number of23ways where logical constness and physical constness coincide:24 25* reading a member variable of builtin type26 27Specifically, this check will not suggest to add a ``const`` to a non-const28method if the method reads a private member variable of pointer type because29that allows to modify the pointee which might not preserve logical constness.30For the same reason, it does not allow to call private member functions31or member functions on private member variables.32 33In addition, this check ignores functions that34 35* are declared ``virtual``36* contain a ``const_cast``37* are templated or part of a class template38* have an empty body39* do not (implicitly) use ``this`` at all40 (see :doc:`readability-convert-member-functions-to-static41 <../readability/convert-member-functions-to-static>`).42 43The following real-world examples will be preserved by the check:44 45.. code-block:: c++46 47 class E1 {48 Pimpl &getPimpl() const;49 public:50 int &get() {51 // Calling a private member function disables this check.52 return getPimpl()->i;53 }54 ...55 };56 57 class E2 {58 public:59 const int *get() const;60 // const_cast disables this check.61 S *get() {62 return const_cast<int*>(const_cast<const C*>(this)->get());63 }64 ...65 };66 67After applying modifications as suggested by the check, running the check again68might find more opportunities to mark member functions ``const``.69