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?
new
and from the OS. It's common fornew
to be implemented as a sub-allocator; it only asks the OS for big memory blocks and sub-divides it when the program needs smaller blocks. – MSalters