llvm / llvm/llvm-project

clang-tidy: add rule: forbid inheriting from classes with non-virtual destructors

Open
#183,101 9 comments 2 reactions 1 assignee Claimed by @CarvedCoder View on GitHub
check-request clang-tidy
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

## goal

In my project, I want to disallow the following memory leak:

1. class `A` has a non-virtual destructor
2. class `B` inherits from class `A`, and has data members
3. someone calls `delete` upon an `A*` that points to an instance of `B`

that is:

```cpp
class A {};
class B : public A
{
int data;
};

A* a = new B();
delete a; //leaks B::data, because A::~A() is not virtual.

```

## ideas for implementation

There are multiple ways to implement this.

The actual precise rule would be kinda complicated:

> Disallow inheriting from a type (class or struct) when the destructor on all base-most types (remember multiple inheritance 😵‍💫) up the inheritance chain are not `virtual`, **and** the inheriting type contains data members.

A very simple good-enough rule, however, would be:

> Require `override` keyword on destructors of all types (classes or structs) that inherit from any other type.

The compiler would then catch the rest.
Would have some false-failures, because there's "no harm, no foul" cases where inheriting classes add no data members and have no side-effects in destructors. But, fine, those are rare, and I'd happily hand-exempt those if I had this rule.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.