cplusplus.co.il

Public operator new and private operator delete

Posted on: 01/12/2009

If you ever try to define a public custom operator new 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 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?

Advertisements

1 Response to "Public operator new and private operator delete"

Looks like googling this up will get you to the same question on stackoverflow, along with its answer..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: