RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Advanced
Aug 2, 2006

The Added Benefit of Using New Instead of Malloc

It's common knowledge that you should avoid using the malloc function in C++. Most programmers use new in its place. The biggest advantage to using new is that it not only allocates memory (what malloc does), but it also calls the appropriate constructor.

Here's an example: suppose you've got a class named CPP and a constructor called CPP(int i);. Here's your original code:

CPP* p = new CPP(10); 
In response, your compiler generates this:

CPP* p = (CPP*) operator new(sizeof(CPP));  
                     // this is operator new which will get you 
                     // the required memory.
 try {
   new(p) CPP(10);   // placement new, actually it calls the  
                     // constructor and uses the space provided by 
                     // the parameter to initialize the data. 

catch (...) {
   operator delete(p);  // Deallocate the memory
   throw;           // Re-throw the exception
Pankaj Mishra
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date