AutosarC++17_03-A12.4.1

Destructor of a base class shall be public virtual, public override or protected non-virtual

Required inputs: IR

Rationale

If an object is supposed to be destroyed through a pointer or reference to its base class, the destructor in the base class needs to be virtual. Otherwise, destructors for derived types will not be invoked.

Note that if it is prohibited to destroy an object through a pointer or reference to its base class, the destructor in the base class is supposed to be protected.

Example
// $Id: A12-4-1.cpp 271687 2017-03-23 08:57:35Z piotr.tanski $
class A {
public:
~A() // Non-compliant
{}
};
class B : public A {};
class C {
public:
virtual ~C() // Compliant
{}
};
class D : public C {};
class E {
protected:
~E(); // Compliant
};
class F : public E {};
void f1(A *obj1, C *obj2) {
// ...
delete obj1; // Only destructor of class A will be invoked
delete obj2; // Both destructors of D and C will be invoked
}
void f2() {
A *a = new B;
C *c = new D;
f1(a, c);
}
See Also
  • JSF December 2005 [7]: AV Rule 78 All base classes with a virtual function shall define a virtual destructor.
  • HIC++ v4.0 [8]: 12.2.1 Declare virtual, private or protected the destructor of a type used as a base class.
  • C++ Core Guidelines [10]: C.35: A base class destructor should be either public and virtual, or protected and nonvirtual.
  • C++ Core Guidelines [10]: Discussion: Make base class destructors public and virtual, or protected and nonvirtual.

Possible Messages

Key

Text

Severity

Disabled

base_class_destructor

Destructor of a base class shall be public virtual, public override or protected non-virtual.

None

False

Options

allowed_inheriting_classes

allowed_inheriting_classes

Type: set[bauhaus.analysis.config.QualifiedName]

Default: {'std::_Compressed_pair', 'std::__compressed_pair_elem', 'std::__detail::_Hashtable_ebo_helper', 'std::__libcpp_compressed_pair_imp', 'std::__map_value_compare', 'std::__unordered_map_hasher'}

A set of full qualified type names that are ignored when determining whether a class is a base class or not. This is mainly a workaround for some libc++ implementation details: The standard library uses private inheritance from empty base classes to implement EBO (Empty Base Optimization) for some of its data structures.