| 1 |
.. title:: clang-tidy - cppcoreguidelines-avoid-const-or-ref-data-members |
| 2 |
|
| 3 |
cppcoreguidelines-avoid-const-or-ref-data-members |
| 4 |
================================================= |
| 5 |
|
| 6 |
This check warns when structs or classes have const-qualified or reference |
| 7 |
(lvalue or rvalue) data members. Having such members is rarely useful, and |
| 8 |
makes the class only copy-constructible but not copy-assignable. |
| 9 |
|
| 10 |
Examples: |
| 11 |
|
| 12 |
.. code-block:: c++ |
| 13 |
|
| 14 |
// Bad, const-qualified member |
| 15 |
struct Const { |
| 16 |
const int x; |
| 17 |
} |
| 18 |
|
| 19 |
// Good: |
| 20 |
class Foo { |
| 21 |
public: |
| 22 |
int get() const { return x; } |
| 23 |
private: |
| 24 |
int x; |
| 25 |
}; |
| 26 |
|
| 27 |
// Bad, lvalue reference member |
| 28 |
struct Ref { |
| 29 |
int& x; |
| 30 |
}; |
| 31 |
|
| 32 |
// Good: |
| 33 |
struct Foo { |
| 34 |
int* x; |
| 35 |
std::unique_ptr<int> x; |
| 36 |
std::shared_ptr<int> x; |
| 37 |
gsl::not_null<int> x; |
| 38 |
}; |
| 39 |
|
| 40 |
// Bad, rvalue reference member |
| 41 |
struct RefRef { |
| 42 |
int&& x; |
| 43 |
}; |
| 44 |
|
| 45 |
The check implements |
| 46 |
`rule C.12 of C++ Core Guidelines <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c12-dont-make-data-members-const-or-references>`_. |
| 47 |
|
| 48 |
Further reading: |
| 49 |
`Data members: Never const <https://quuxplusone.github.io/blog/2022/01/23/dont-const-all-the-things/#data-members-never-const>`_. |