Reputation: 297
Basically I have a class A which creates an array upon construction.
class A
{
public:
A (float height, float width, BYTE* data)
{
setsize(height,width);
mydata = CreateNewBuffer(sizes);
setdata(data);
}
~A()
{
}
void setsize(float height, float width)
{
sizes.cx = width;
sizes.cy = height;
}
BYTE* CreateNewBuffer (SIZE sImage)
{
return new BYTE [sImage.cx * sImage.cy];
}
void setdata(BYTE* data)
{
memcpy(threatdata,data,sImage.cx * sImage.cy);
}
}
I create a pointer to this class in bigger class:
A* mypointer;
which I initialize in a 3rd class after passing it through a function:
3rdClass::instance()->myfunction(mypointer)
and inside the function myfunction() I set a bool indicating the class was constructed
mypointer = new A(height,width,data);
wasconstructed = true;
Now the next time I come to the passing the pointer to the function myfunction()
, I check if the class was already constructed, if it was, I want to delete it so that it creates a new one without memory loss.
What is the proper way to do this:
I tried basic stuff like,
if (3rdClass::instance()->checkifconstructed()){
delete mypointer; //(or even delete [] mypointer but then i get heap corruption)
mypointer = NULL;
}
But that does not seem to work.
Upvotes: 3
Views: 498
Reputation: 92391
If the constructor new[] some data, the destructor should delete[] it again.
You should also consider what happens if you copy or assign to an object of the class. Do you need create a new set of data and copy the values from then original object?
Upvotes: 1
Reputation: 21818
I assume that mydata
is a member of your class (otherwise, what is mydata
in the 7-th line of your code?)
So, the dynamic array is a member of your class. If you want to destroy it when the containing object is destroyed, you should do exactly that: order the destruction of your member in the destructor of your class. Something like:
~A()
{
delete [] mydata;
}
Now, when you invoke delete mypointer
it will invoke the destructor of the class, which will destroy the array.
Upvotes: 4