4

Possible Duplicate:
Deleting 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's understandable that free() is a function, so a const void* cannot be converted to void*. But why is it allowed in the case of operator delete (default or overloaded) ?

Is it not functionally a wrong construct ?

Community
  • 1
  • 1
iammilind
  • 68,093
  • 33
  • 169
  • 336

2 Answers2

4

It's not. The delete expression first calls the destructor. After destruction, you are left with a void*. (The typical implementation, in fact, has the destructor call the operator delete() function, since which operator delete() to call depends on the most derived class.)

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

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

? One can argue for different rules, but in the end, destructors are special, and obey special rules.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
2

While I quite agree with @JamesKanze's answer, perhaps somebody would like to see what the standard actually says. According to the standard (§12.1/4):

const and volatile semantics (7.1.5.1) are not applied on an object under construction. Such semantics only come into effect once the constructor for the most derived object (1.8) ends.

and (§12.4/2):

const and volatile semantics (7.1.5.1) are not applied on an object under destruction. Such semantics stop being into effect once the destructor for the most derived object (1.8) starts.

In fairness, this does little more than re-state what @James said, a bit more specifically: the object is only really considered an object from the time the ctor finishes (or all the ctors, when inheritance is involved) to the point that the first dtor begins. Outside those boundaries, const and volatile aren't enforced.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • There's a subtle difference. James says, "*After* destruction, you are left with a `void*`. " Standard says, "Such semantics stop being into effect once the destructor for the most derived object (1.8) starts." So, from what James said, someone could *infer* that `const` semantics were still in effect during destructor execution, and be wrong. It's really nitpicking, though. – Mike DeSimone Nov 15 '11 at 22:24