Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting a pointer to a class which creates an array

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.

like image 403
Simon Avatar asked Jul 25 '26 05:07

Simon


2 Answers

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.

like image 118
CygnusX1 Avatar answered Jul 26 '26 22:07

CygnusX1


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?

like image 24
Bo Persson Avatar answered Jul 26 '26 21:07

Bo Persson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!