AUTOSAR C++14 Rule A12-4-2
If a public destructor of a class is non-virtual, then the class should be declared final
Since R2020b
Description
Rule Definition
If a public destructor of a class is non-virtual, then the class should be declared final.
Rationale
In C++, when any object of a derived class is destroyed, first the destructor of its
class is invoked, and then the destructors of the base classes are invoked. Class
hierarchies can also be polymorphic. You can declare a base class pointer and assign a
derived class object to it. To safely destroy objects belonging to a class hierarchy,
declare the public
class destructors as virtual
.
Consider this code where two base class pointers that point to derived objects are destroyed.
class Base{ public: virtual ~Base(); //.. }; class Derived : public Base{ public: ~Derived(); //.. }; class Base2{ public: ~Base2(); //.. }; class Derived2 : public Base2{ public: ~Derived2(); //... }; int main(){ Base* ptr = new Derived; Base2* ptr2 = new Derived2; delete ptr; delete ptr2; }
The object
ptr
is a pointer of classBase
that points to an object of classDerived
. Whenptr
is deleted, the destructor of the derived class is called first, and then the destructor of the base class is called. Even thoughptr
is a base class object, the correct destructors are called to release all acquired resources because thepublic
destructors in this class hierarchy are declared asvirtual
.When the pointer
ptr2
is deleted, the destructor of only the base class is called because thepublic
destructors in this class hierarchy are nonvirtual. This kind of incomplete destruction is undefined behavior, which can lead to memory leaks and unexpected termination of code execution.
To prevent undefined behavior, do not use classes with
public
nonvirtual destructors as base classes. Declare such classes as
final
to specify that these classes are not base classes and new
classes cannot be derived from them.
Polyspace Implementation
Polyspace® flags a class declaration if both these statements are true:
The
public
destructor of the class is not declared asvirtual
.The class is not declared
final
.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Special member functions |
Category: Advisory, Automated |
Version History
Introduced in R2020b