#include <iostream>
class ArrayClass
{
private:
int *m_Arr;
int i;
public:
int Size;
ArrayClass() : Size(5), i(0), m_Arr(nullptr)
{
std::cout << "The constructor was called." << std::endl;
}
~ArrayClass()
{
std::cout << "The destructor was called." << std::endl;
delete[] m_Arr;
}
void InitArr()
{
m_Arr = new int[Size];
}
void Setter(int &var)
{
*(m_Arr + i) = var;
i++;
}
int *Getter() const
{
return m_Arr;
}
};
int main()
{
ArrayClass *instance = new ArrayClass[2];
std::cout << instance << std::endl;
for (int j = 0; j < 2; j++)
{
(instance + j)->InitArr();
for (int i = 1; i <= (instance + j)->Size; i++)
{
(instance + j)->Setter(i);
}
int *Get = (instance + j)->Getter();
std::cout << "The numbers are:" << std::endl;
for (int i = 0; i < (instance + j)->Size; i++)
{
std::cout << *(Get + i) << std::endl;
}
}
for (int l = 0; l < 2; l++)
{
delete (instance + l);
}
std::cin.get();
return 0;
}
I am a beginner in C++, and have ran into a problem, I am trying to use the delete keyword, using the for loop, instead of delete[] instance. I am just trying to keep this method of deleting the instance array in heap, using the pointer arithmetic. But the delete is not doing the work, when I run the program, the destructor code snippet is not printed out on the cmd, the program just terminates, not respecting the line std::cin.get();
Only, doing this works. delete[] instance;
.
But, I want this method to be used,
for (int l = 0; l < 2; l++)
{
delete (instance + l);
}
So, can you please rectify the mistake.
Or, is it that the method I am trying to use, even valid in C++
Unfortunately method you want to use isn't valid in C++.
You need to use delete
to free memory for object created with new
, and delete[]
to free memory for array created with new[]
. Simple mnemonic - for each new
one delete
, for each new[]
one delete[]
.
The reason for this that when you create something with new
or new[]
you allocate a bit more memory than you expect, additional memory is allocated for technical information for delete
or delete[]
operator. This information specify amount of memory that was allocated and which should be later deleted with operator delete
or delete[]
. And when you use delete
for each element of array allocated with new[]
the delete
operator looks in a wrong place for technical information and this can lead to undefined behavior.
This is simple explanation, for more precise I advice you to look on cppreference.com, but for the beginning I believe this explanation is enough