C++ Logo

std-proposals

Advanced search

Re: Make abstract classes non-deletable if no virtual destructor available

From: Michał Policht <michal_at_[hidden]>
Date: Wed, 25 Mar 2020 14:29:45 +0100
This closes protected dtors path.

What I really don't like is that this is incomplete solution. From
social perspective it may even do more evil than good. Think about
inexperienced programmer, who realizes that he can either provide
virtual dtor or... provide default implementation for pure virtual
method to "fix" an error... Inexperienced programmers perceive it as a
win to just "outsmart" a compiler. When code, which didn't compile
suddenly compiles and program seems to work they're assured that they've
done everything right.

And for the same reason I see no benefit for more experienced
programmers. If I can't rely on a feature, which works in all cases and
instead it works only in some specific cases, then IMO it's better to
have no such feature at all - so that I know what I can expect and stay
focused. Your proposal is like a little kid trying to help me a bit to
carry shopping bags, but he can only carry a small box of chocolates, so
IDK if he really helps me or just annoys me :)

Regards
Michał


> While my initial proposal would require changing the C++ language, a
> (not equal but similar) approach would be
> to only change the implementation of std::default_delete to:
>
> template<class T>
> struct default_delete {
> void operator()(T* ptr) {
> static_assert(!is_abstract_v<T> || has_virtual_destructor_v<T>);
> delete ptr;
> }
> };
>
> As (hopefully) most people use a abstract base class together with
> unique_ptr,
> this would also make the language more safe.
>
>
>
> On Mon, Mar 23, 2020 at 3:19 PM Kilian Henneberger via Std-Proposals
> <std-proposals_at_[hidden] <mailto:std-proposals_at_[hidden]>>
> wrote:
>
> Hello,
>
> an abstract class (a class that either defines or inherits at least one
> function for which the final overrider is pure virtual)
> cannot be instantiated. However it can be destroyed. But deleting a
> Derived-object through a pointer to Base-object
> leads to undefined behaviour if the destructor of the Base-class is not
> virtual.
> There also exists a CppCoreGuideline addressing this topic:
> http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-dtor-virtual
>
> I want to propose that we make the attempt to delete a pointer to an
> abstract class ill-formed,
> if the abstract class does not have a (public) virtual destructor.
>
> This would turn what currently is UB into a compiler error.
> But it also might imply that code which compiles today (even if leading
> to UB), wont compile any longer after this change.
>
> I am looking forward to any feedback.
> Best regards,
> Kilian Henneberger
>
>
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden] <mailto:Std-Proposals_at_[hidden]>
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>
>
>
>

Received on 2020-03-25 08:32:38