1.. title:: clang-tidy - readability-make-member-function-const 2 3readability-make-member-function-const 4====================================== 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 to 10`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-const 13method only if this method does something that is already possible though the 14public interface on a ``const`` pointer to the object: 15 16* reading a public member variable 17* calling a public const-qualified member function 18* 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-const 22method if this method uses private data and functions in a limited number of 23ways where logical constness and physical constness coincide: 24 25* reading a member variable of builtin type 26 27Specifically, this check will not suggest to add a ``const`` to a non-const 28method if the method reads a private member variable of pointer type because 29that allows to modify the pointee which might not preserve logical constness. 30For the same reason, it does not allow to call private member functions 31or member functions on private member variables. 32 33In addition, this check ignores functions that 34 35* are declared ``virtual`` 36* contain a ``const_cast`` 37* are templated or part of a class template 38* have an empty body 39* do not (implicitly) use ``this`` at all 40 (see `readability-convert-member-functions-to-static <readability-convert-member-functions-to-static.html>`_). 41 42The following real-world examples will be preserved by the check: 43 44.. code-block:: c++ 45 46 class E1 { 47 Pimpl &getPimpl() const; 48 public: 49 int &get() { 50 // Calling a private member function disables this check. 51 return getPimpl()->i; 52 } 53 ... 54 }; 55 56 class E2 { 57 public: 58 const int *get() const; 59 // const_cast disables this check. 60 S *get() { 61 return const_cast<int*>(const_cast<const C*>(this)->get()); 62 } 63 ... 64 }; 65 66After applying modifications as suggested by the check, running the check again 67might find more opportunities to mark member functions ``const``. 68