How many times do new [] and delete[] make calls to allocate and deallocate memory?

  • A+

In C++, for every time new [] is used or delete [] is used, how many times does each one allocate or deallocate memory? My question is more specific to using them on classes with their respective constructors and destructor.

Such as, take the following class:

#include <iostream>  class Cell { public:     Cell() : _value(2)     {         std::cout << "Cell being made!/n";     }     ~Cell()     {         std::cout << "Cell being freed!/n";     }      const int& getVal() const     {         return _value;     } private:     int _value; }; 

Now, say an array of that class type is needed, and new[] is used, as below

Cell* cells = new Cell[5]; 

When this is run in an executable or program, I also see the following printed to stdout:

Cell being made! Cell being made! Cell being made! Cell being made! Cell being made! 

And subsequently when delete[] is called on the cells pointer, I see:

Cell being freed! Cell being freed! Cell being freed! Cell being freed! Cell being freed! 

My question is, in every constructor call, is the size of memory equal to one class instance being allocated? Such as does new Cell[5] allocate memory 5 times? Or does it allocate once and then make 5 calls to the constructor as just a function call? Same with delete[], does it deallocate at every destructor call?


You are mixing two different concepts:

  1. Memory allocation/deallocation
  2. Object construction/destruction

new and delete do both for us.

new Cell[5];

Total memory needed for all 5 objects are allocated in a single memory allocation operation. It can't be 5 allocations as 5 different allocations can't guarantee consecutive spaces.

After allocating memory for 5 objects, new must initialize 5 objects by calling default constructor. Here we have 5 separate constructor calls.

Similar things happen during delete [] cells. It have to destroy 5 objects by calling destructor of 5 different objects. Then all allocated memory is freed in one single deallocation operation.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: