Skip to content

FR: Off-by-default Clang warning when publicly inheriting from a class with public non-virtual dtor #131693

@pkasting

Description

@pkasting

Publicly inheriting from a class with a (possibly autogenerated) public, non-virtual dtor risks incorrect behavior if an instance is deleted through the base class destructor.

#include <memory>

struct Base {};
struct Derived : Base {};

void f() {
  std::unique_ptr<Base> ptr = std::make_unique<Derived>();
  ptr.reset();  // ~Derived() not called; negative consequences depend on actual struct contents
}

We already have -Wnon-virtual-dtor and -Wdelete-non-virtual-dtor, but neither catch this, because they're focused on cases where there is a vtable. At least in Chromium, it's not unknown to "extend" existing classes that lack vtables by inheriting from them, hence the desire for this warning.

The author would be expected to fix by either making ~Base() protected or virtual (or by using composition instead of inheritance).

One way to reduce warning instances on "clearly harmless" cases would be to omit this warning when the derived class is scoped to something the compiler can see all of (e.g. inside an anonymous namespace) and is never heap-allocated in that scope. That might be too complex to implement, though.

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:diagnosticsNew/improved warning or error message in Clang, but not in clang-tidy or static analyzer

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions