Skip to content

deleting a pointer when the static type and dynamic types are similar is potentially UB CWG2474 #4305

@leni536

Description

@leni536

http://eel.is/c++draft/expr.delete#3

In a single-object delete expression, if the static type of the object to be deleted is different from 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 differs from its static type, the behavior is undefined.

"static type" and "dynamic type" includes cv qualification. By the standard wording invoking foo and bar is undefined behavior in the following code:

struct A {};
void foo() {
    A* ptr = new A{};
    const A* cptr = ptr;
    delete cptr;
}

void bar() {
    int i = 42;
    int ** ptr1 = new int*(&i);
    int const * const* ptr2 = ptr1;
    delete ptr2; 
}

Proposed changes:

In a single-object delete expression, if the static type of the object to be deleted is different from not similar 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 differs from is not similar to its static type, the behavior is undefined.

Metadata

Metadata

Assignees

No one assigned

    Labels

    cwgIssue must be reviewed by CWG.not-editorialIssue is not deemed editorial; the editorial issue is kept open for tracking.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions