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.
I assume that
mydatais a member of your class (otherwise, what ismydatain 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:
Now, when you invoke
delete mypointerit will invoke the destructor of the class, which will destroy the array.