My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping @Yeyhi.com









Tuesday, June 1, 2010

Overriding New and Delete Operators

Recently in Acrobat Team of Adobe Systems, I was amidst a situation in which I had to overload the “new” and “delete” operators. This came like a thunderstorm to me initially, but merely a second thought gave me some comfort. And hola!! Within two hours I was with complete implementation of the Idea. I have written this as my new story because , For most programming tasks, the default implementation of new and delete is sufficient. In fact, many C++ programmers get along without even knowing that they can override these operators.

I have really come to conclusion that modifying these operators for a given class is essential in certain advanced programming tasks. One example might be when you need to ensure that all instances of a class are allocated from a custom memory pool instead of the free-store.

There are other useful applications of overriding new and delete: implementing a garbage collector, or ensuring that objects are allocated on a specific memory address.

My design is as follows:

class A
{
public:
A();
~A();
static void* operator new (size_t size);
{
void *p=allocate_from_pool(size);
return p;
}

static void operator delete (void *p);
{
release(p);
}

};

THe real use come when you write some additional tasks in these functions. The easiest and most commonly used tasks could be refCount or logging in some file, etc.

Remember that when you declare new and delete as class members, they are implicitly declared static. Still, it's advisable to add the keyword static to their declarations to document this property explicitly.

Again it is important to remember that C++ guarantees that an object's destructor is automatically called just before delete executes. Therefore, you shouldn't invoke A's destructor explicitly. In case you do so, it would cause undefined behavior as the destructor will actually run twice.

Now this implementation can actually be used in your personal or professional work. Just don’t stop thanking me for this. ;)

2 comments:

  1. Thankyou for this great tutorial. I needed this in one of my project in Bangalore.

    ReplyDelete
  2. Thanks Fahad!!

    I got your email about how you used this article as a quick head-start in your project.
    I will publish soon the details as a case study!!

    ReplyDelete