4

I notice that the declaration of delete in the directory of gcc source gcc/libstdc++-v3/libsupc++/newis

    void operator delete(void*)
    void operator delete[](void*)

Why can we pass const ptr to the operator?

    const int* a = new int(1);
    delete(a);

I think void* and const int* are incompatible types.

cnby
  • 389
  • 4
  • 15
  • 1
    Note the difference between [`delete` _expression_](https://en.cppreference.com/w/cpp/language/delete) and [`operator delete`](https://en.cppreference.com/w/cpp/memory/new/operator_delete). – Daniel Langr Jan 21 '20 at 08:57
  • Construction/destruction isn't const restricted. Consider `const Foo foo;`, where `Foo` is an object class type. The result is a `foo` where you can only access `const` members. The object itself is still constructible, and must be destructible as well. That you're doing this *dynamically* is really the only difference. Edit: pretty sure [this is a dupe](https://stackoverflow.com/questions/755196/deleting-a-pointer-to-const-t-const) of your question. – WhozCraig Jan 21 '20 at 08:59

1 Answers1

5

You are right. Normally, const int* cannot be implicitly converted into void* (in order to respect the const-correctness).

However, from the standard [expr.delete]:

[ Note: A pointer to a const type can be the operand of a delete-expression; it is not necessary to cast away the constness of the pointer expression before it is used as the operand of the delete-expression. — end note ]

In order words, the expression delete expr is automatically handled by the compiler regarding the const-correctness.

Different story, for example, if you try to directly call the function, such as:

::operator delete(p);
BiagioF
  • 9,368
  • 2
  • 26
  • 50
  • Thanks for answer. Could you please explain more about how the compiler "handle `const` qualifier" ? Just discard it as a special case? Or there is some priority mechanism between `delete` and `const`? – cnby Jan 21 '20 at 11:16
  • `const` attribute is just an artificial construct parsed by the compiler. In the case of `delete` expression, the compiler just ignore the `const`. – BiagioF Jan 21 '20 at 11:42