Why is "const T *" trivially converted to "void *" to "delete operator"?

Possible duplicate:
Removing a pointer to const (T const *)

void operator delete (void*); ... const char *pn = new char, *pm = (char*)malloc(1); delete pn; // allowed !! free(pm); // error 

Demo

It is clear that free() is a function, therefore a const void* cannot be converted to void* . But why is this allowed in the case of operator delete (default or overloaded)?

Is this a malfunctioning design?

+4
source share
2 answers

While I completely agree with @JamesKanze's answer, maybe someone will want to see what the standard actually says. According to the standard (ยง12.1 / 4):

const and unstable semantics (7.1.5.1) do not apply to an object under construction. Such semantics takes effect only after the constructor for the most derived object (1.8) ends.

and (ยง12.4 / 2):

const and volatile semantics (7.1.5.1) do not apply to destructible objects. Such semantics ceases to be effective after the destructor is launched for the derived object (1.8).

In fairness, this does nothing more than re-articulating what @James said, a little more specifically: an object is really only considered an object from the moment ctor (or all ctors when inheritance is involved) completes, the point at which the first dtor begins. Outside of these boundaries, const and volatile do not apply.

+2
source

This is not true. The delete first calls the destructor. After destruction, you will be left with void* . (A typical implementation, in fact, the destructor calls the operator delete() function, since calling operator delete() to call depends on the derived class itself.)

As for why your T const* becomes T* in the destructor: this is any different than:

 { T const anObject; // ... } // destructor of anObject called here. With T*, not T const* 

? You can argue according to different rules, but, in the end, destructors are special and follow special rules.

+4
source

Source: https://habr.com/ru/post/1381314/


All Articles