https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114245
Bug ID: 114245
Summary: Defaulted virtual destructors that do no work
overwrite the vtable with `-O0`
Product: gcc
Version: 13.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: mwinkler at blizzard dot com
Target Milestone: ---
https://godbolt.org/z/Ge135h6qh
Use the godbolt for reference against all the 3 major compilers,
GCC/Clang/MSVC.
The following bug report is only for `-O0` builds.
Optimized builds end up removing the dead vtable stores but we require our
debug builds to behave the same as release builds.
Given a virtual destructor that is defaulted and does no work GCC will
overwrite the vtable with the current objects most constructed type.
This behaviour isn't required by MSVC or Itanium CXX ABI or the C++ std but it
would be nice to have all 3 major compilers agree here especially since MSVC
and Clang both have this behaviour.
```
struct Base { virtual ~Base() = default; };
struct Derived : Base { virtual ~Derived() = default; };
```
In the example above `~Derived` will overwrite the vtable with the vtable for
Derived. `~Base` will overwrite the vtable with the vtable for Base.
If you have a global object of `Derived` you easily run into static de-init
fiasco issues since these objects are also registered with `__cxa_atexit`.
Clang and MSVC for defaulted virtual destructors do not overwrite the vtable in
the generated destructors even though they still register with `__cxa_atexit`
so the running of the destructor ends up being a nop.
Clang also has the `[[clang::no_destroy]]` attribute.
We have a workaround on GCC by doing the following for such global objects.
```
union NoDestroy
{
Derived v;
constexpr NoDestroy() : v() {}
~NoDestroy() {}
};
```
There are two solutions that will work for our use case.
Add a similar attribute like `[[clang::no_destroy]]` to mark certain global
objects that should not be registered with `__cxa_atexit`. I couldn't find such
a similar attribute in the GCC docs.
Have GCC behave like MSVC and Clang here when optimizations are disabled and
have defaulted virtual destructors not overwrite the vtable.
Thanks :).