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}
Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular