Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Advanced
Apr 6, 1999

Overload New and Delete in a Class

It is possible to override the global operators new and delete for a given class. For example, you can use this technique to override the default behavior of operator new in case of a failure. Instead of throwing a std::bad_alloc exception, the class-specific version of new throws a char array:
 
#include <cstdlib> //declarations of malloc and free
#include <new>
#include <iostream>
using namespace std;

class C {
public:
  C(); 
  void* operator new (size_t size); //implicitly declared as a static member function
  void operator delete (void *p); //implicitly declared as a static member function
};

void* C::operator new (size_t  size) throw (const char *){
  void * p = malloc(size);
  if (p == 0)  throw "allocation failure";  //instead of std::bad_alloc
  return p; 
}

void C::operator delete (void *p){	
  C* pc = static_cast<C*>(p); 
  free(p);	
}

int main() { 
   C *p = new C; // calls C::new
   delete p;  // calls C::delete
}
Note that the overloaded new and delete implicitly invoke the object's constructor and destructor, respectively. Remember also to define a matching operator delete when you override operator new.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap