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}
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist