[cfe-dev] is delete on abstract with non-virtal ever safe?
Matthieu Monrocq
matthieu.monrocq at gmail.com
Sat Oct 5 08:49:41 PDT 2013
On Sat, Oct 5, 2013 at 5:38 PM, Tim Northover <t.p.northover at gmail.com>wrote:
> > This doesn’t mean by chance there is no destructor so nothing bad
> happens,
> > it mean if there is no destructor so, according to the standard, the
> > compiler should consider the object alive until the memory is released.
>
> There are multiple sub-objects under discussion here and only one of
> them has a trivial destructor.
>
> The standard appears to have stopped specifying behaviour at 5.3.5
> ("thou shalt have a virtual destructor") so the entire discussion is
> moot. But I think it's difficult to argue that, had it skipped that
> bit and gone on to define behaviour for your case, either the
> my_destroy_default_impl or Toto objects would still be alive.
>
> Tim.
>
Ah, thanks. It seems that this is actually re-iterated later on, so let's
have both quotes:
§5.3.5 Delete [expr.delete]
3/ In the first alternative (delete object), if the static type of the
object to be deleted is different from its dynamic type, 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.
§12.5 Free store [class.free]
4 [...] Otherwise, if the delete-expression is used to deallocate a class
object whose static type has a virtual destructor, the deallocation
function is the one selected at the point of definition of the dynamic
type’s virtual destructor (12.4). Otherwise, if the delete-expression is
used to deallocate an object of class T or array thereof, the static and
dynamic types of the object shall be identical and the deallocation
function’s name is looked up in the scope of T.
So the Standard is unambiguous: either `delete` shall be called on a
pointer to the most derived object or, if called on a base sub-object, the
destructor of the corresponding sub-class shall be virtual.
On the other, the good news for you Emmanuel is the first sentence of
§12.5/4 I cited: when calling `delete base`, the `delete` operator called
is looked up at the point of definition of the dynamic type's virtual
destructor. Thus your usecase of linking two libraries with incompatible
new/delete pairs should work as-is providing you take care that the virtual
dispatch to the destructor selects the right definition of operator delete.
-- Matthieu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20131005/8bb33a90/attachment.html>
More information about the cfe-dev
mailing list