devxlogo

The Added Benefit of Using New Instead of Malloc

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}

devx-admin

Share the Post: