| 1 |
.. title:: clang-tidy - bugprone-copy-constructor-init |
| 2 |
|
| 3 |
bugprone-copy-constructor-init |
| 4 |
============================== |
| 5 |
|
| 6 |
Finds copy constructors where the constructor doesn't call the copy constructor |
| 7 |
of the base class. |
| 8 |
|
| 9 |
.. code-block:: c++ |
| 10 |
|
| 11 |
class Copyable { |
| 12 |
public: |
| 13 |
Copyable() = default; |
| 14 |
Copyable(const Copyable &) = default; |
| 15 |
|
| 16 |
int memberToBeCopied = 0; |
| 17 |
}; |
| 18 |
|
| 19 |
class X2 : public Copyable { |
| 20 |
X2(const X2 &other) {} // Copyable(other) is missing |
| 21 |
}; |
| 22 |
|
| 23 |
Also finds copy constructors where the constructor of |
| 24 |
the base class don't have parameter. |
| 25 |
|
| 26 |
.. code-block:: c++ |
| 27 |
|
| 28 |
class X3 : public Copyable { |
| 29 |
X3(const X3 &other) : Copyable() {} // other is missing |
| 30 |
}; |
| 31 |
|
| 32 |
Failure to properly initialize base class sub-objects during copy construction |
| 33 |
can result in undefined behavior, crashes, data corruption, or other unexpected |
| 34 |
outcomes. The check ensures that the copy constructor of a derived class |
| 35 |
properly calls the copy constructor of the base class, helping to prevent bugs |
| 36 |
and improve code quality. |
| 37 |
|
| 38 |
Limitations: |
| 39 |
|
| 40 |
* It won't generate warnings for empty classes, as there are no class members |
| 41 |
(including base class sub-objects) to worry about. |
| 42 |
|
| 43 |
* It won't generate warnings for base classes that have copy constructor |
| 44 |
private or deleted. |
| 45 |
|
| 46 |
* It won't generate warnings for base classes that are initialized using other |
| 47 |
non-default constructor, as this could be intentional. |
| 48 |
|
| 49 |
The check also suggests a fix-its in some cases. |