| 1 |
.. title:: clang-tidy - cppcoreguidelines-virtual-class-destructor |
| 2 |
|
| 3 |
cppcoreguidelines-virtual-class-destructor |
| 4 |
=============================================== |
| 5 |
|
| 6 |
Finds virtual classes whose destructor is neither public and virtual |
| 7 |
nor protected and non-virtual. A virtual class's destructor should be specified |
| 8 |
in one of these ways to prevent undefined behavior. |
| 9 |
|
| 10 |
This check implements |
| 11 |
`C.35 <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-dtor-virtual>`_ |
| 12 |
from the CppCoreGuidelines. |
| 13 |
|
| 14 |
Note that this check will diagnose a class with a virtual method regardless of |
| 15 |
whether the class is used as a base class or not. |
| 16 |
|
| 17 |
Fixes are available for user-declared and implicit destructors that are either |
| 18 |
public and non-virtual or protected and virtual. No fixes are offered for |
| 19 |
private destructors. There, the decision whether to make them private and |
| 20 |
virtual or protected and non-virtual depends on the use case and is thus left |
| 21 |
to the user. |
| 22 |
|
| 23 |
Example |
| 24 |
------- |
| 25 |
|
| 26 |
For example, the following classes/structs get flagged by the check since they |
| 27 |
violate guideline **C.35**: |
| 28 |
|
| 29 |
.. code-block:: c++ |
| 30 |
|
| 31 |
struct Foo { // NOK, protected destructor should not be virtual |
| 32 |
virtual void f(); |
| 33 |
protected: |
| 34 |
virtual ~Foo(){} |
| 35 |
}; |
| 36 |
|
| 37 |
class Bar { // NOK, public destructor should be virtual |
| 38 |
virtual void f(); |
| 39 |
public: |
| 40 |
~Bar(){} |
| 41 |
}; |
| 42 |
|
| 43 |
This would be rewritten to look like this: |
| 44 |
|
| 45 |
.. code-block:: c++ |
| 46 |
|
| 47 |
struct Foo { // OK, destructor is not virtual anymore |
| 48 |
virtual void f(); |
| 49 |
protected: |
| 50 |
~Foo(){} |
| 51 |
}; |
| 52 |
|
| 53 |
class Bar { // OK, destructor is now virtual |
| 54 |
virtual void f(); |
| 55 |
public: |
| 56 |
virtual ~Bar(){} |
| 57 |
}; |