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 Delete Operator In C++ when we want to allocate memory from the free-store (or we may call it heap) we use the new operator. int *ptr = new int; and to deallocate we use the delete operator.
Using the delete operator on an object deallocates its memory. A program that dereferences a pointer after the object is deleted can have unpredictable results or crash.
Examples: delete p; delete q; To free the dynamically allocated array pointed by pointer variable, use the following form of delete: // Release block of memory // pointed by pointer-variable delete[] pointer-variable; Example: // It will free the entire array // pointed by p.
Only deallocate memory when you are truly finished with that memory. If you have more than one pointer to a chunk of memory, then deallocating that chunk makes all pointers to it stale; they are pointing to memory that you are no longer allowed to use. Those pointers are called dangling pointers.
You are mixing two different concepts:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With