C++ Logo

sg12

Advanced search

Less UB with delete baseptr?

From: Peter Sommerlad (C++) <"Peter>
Date: Sun, 15 Oct 2023 16:01:32 +0200
Hi,

I understand while in general delete baseptr; is UB when the base
doesn't have a virtual destructor (or a destroying operator delete that
does the right thing).

However, I wonder if in the case of trivial destructors for both base
and derived and/or when sizeof(base) == sizeof(derived) there is a need
for making deleting via a base pointer undefined behavior.

The situation where such constructs occur is common with mix-in types or
derived classes that act as adapters to the base class, e.g., by
providing additional interfaces, for example.

Especially with the extended aggregate capabilities it can be attractive
not to introduce a protected destructor in the base class to prevent
derived-to-base pointer conversions.

So my question is, can we reduce the risk of undefined behavior by
changing [expr.delete] p.3

from

"In a single-object delete expression, if the static type of the object
to be deleted is not similar (7.3.6) to its dynamic type and the
selected deallocation function (see below) is not a destroying operator
delete, the static type shall be a base class of the dynamic type of the
object to be deleted and the static type shall have a virtual destructor
or the behavior is undefined. In an array delete expression, if the
dynamic type of the object to be deleted is not similar to its static
type, the behavior is undefined."

to
In a single-object delete expression, if the static type of the object
to be deleted is not similar (7.3.6) to its dynamic type and the
selected deallocation function (see below) is not a destroying operator
delete, the static type shall be a base class of the dynamic type of the
object to be deleted and the static type shall have <ins>either</ins> a
virtual destructor <ins>or both the static type and the dynamic type
shall have a trivial destructor and have the same size, otherwise</ins>
<del>or</del> the behavior is undefined. In an array delete expression,
if the dynamic type of the object to be deleted is not similar to its
static type, the behavior is undefined.


Does it make sense to propose such a change?

Regards
Peter.

-- 
Peter Sommerlad
Better Software: Consulting, Training, Reviews
Modern, Safe & Agile C++
peter.cpp_at_[hidden]
+41 79 432 23 32

Received on 2023-10-15 14:01:36