Public operator new and private operator delete
December 1st, 2009 § 1 Comment
If you ever try to define a public custom new-operator while keeping the corresponding delete-operator private, you’ll end up unable to compile any code that actually invokes the public operator new. The reasoning is quite interesting.
Consider the following code snippet:
#include <cstdlib>
struct Try {
Try () { /* o/ */ }
void *operator new (size_t size) {
return malloc(size);
}
private:
void operator delete (void *obj) {
free(obj);
}
};
int main () {
Try *t = new Try();
return 0;
}
An attempt to compile the code under GCC leads to this error:
antrikot:~/work/sandbox> g++ try.cc try.cc: In function ‘int main()’: try.cc:11: error: ‘static void Try::operator delete(void*)’ is private try.cc:17: error: within this context try.cc:11: error: ‘static void Try::operator delete(void*)’ is private try.cc:17: error: within this context
Although we have never made any (explicit?) use of the private operator delete.
Why does the compiler complain? Take a moment to think this through.
The answer can be found in the comments below.
Looks like googling this up will get you to the same question on stackoverflow, along with its answer..