1 .. title:: clang-tidy - readability-make-member-function-const
3 readability-make-member-function-const
4 ======================================
6 Finds non-static member functions that can be made ``const``
7 because the functions don't use ``this`` in a non-const way.
9 This 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).
12 Therefore, it will suggest to add a ``const`` qualifier to a non-const
13 method only if this method does something that is already possible though the
14 public interface on a ``const`` pointer to the object:
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.
21 This check will also suggest to add a ``const`` qualifier to a non-const
22 method if this method uses private data and functions in a limited number of
23 ways where logical constness and physical constness coincide:
25 * reading a member variable of builtin type
27 Specifically, this check will not suggest to add a ``const`` to a non-const
28 method if the method reads a private member variable of pointer type because
29 that allows to modify the pointee which might not preserve logical constness.
30 For the same reason, it does not allow to call private member functions
31 or member functions on private member variables.
33 In addition, this check ignores functions that
35 * are declared ``virtual``
36 * contain a ``const_cast``
37 * are templated or part of a class template
39 * do not (implicitly) use ``this`` at all
40 (see `readability-convert-member-functions-to-static <../readability/convert-member-functions-to-static.html>`_).
42 The following real-world examples will be preserved by the check:
47 Pimpl &getPimpl() const;
50 // Calling a private member function disables this check.
58 const int *get() const;
59 // const_cast disables this check.
61 return const_cast<int*>(const_cast<const C*>(this)->get());
66 After applying modifications as suggested by the check, running the check again
67 might find more opportunities to mark member functions ``const``.