Why delete can perform on pointers to const while free cannot?

Viewed 6244

I've just noticed that the pointers passed to delete can be const qualified while those passed to free cannot. That is really a surprise to me.

And in C++ an overload to operator delete should have a signature like:

void operator delete(void* p);

But adding a const to the parameter pointer is invalid:

void operator delete(void const* p);

May anyone tell me why delete is designed this way?

5 Answers

In C++, undefined behavior is predicated only on the constness of the object as instantiated, not the presence of a const qualifier along an access path thereto. Thus, const_cast can be used to modify objects behind a pointer of const-qualified target type, so long as the objects were not instantiated const.

Because malloc() instantiates non-const primitive data, it would be completely legal for free() to take a pointer to const, then cast it away and modify the memory as necessary. But because free() predates the const keyword, it does not qualify as it should.

C++ pogrammers may cast away const in order to free malloc'd memory.

Related