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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date