| 1 |
.. title:: clang-tidy - readability-make-member-function-const |
| 2 |
|
| 3 |
readability-make-member-function-const |
| 4 |
====================================== |
| 5 |
|
| 6 |
Finds non-static member functions that can be made ``const`` |
| 7 |
because the functions don't use ``this`` in a non-const way. |
| 8 |
|
| 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: |
| 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 |
|
| 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: |
| 24 |
|
| 25 |
* reading a member variable of builtin type |
| 26 |
|
| 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. |
| 32 |
|
| 33 |
In 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 :doc:`readability-convert-member-functions-to-static <../readability/convert-member-functions-to-static>`). |
| 41 |
|
| 42 |
The 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 |
|
| 66 |
After applying modifications as suggested by the check, running the check again |
| 67 |
might find more opportunities to mark member functions ``const``. |