I have a class called ‘Byte’ that makes me allocate/deallocate dynamic memory.but i am having problem,i don’t know where to free it on destructor ? or code new functions like free()
let me explain.
Byte string; // Default constructor created a heap saved in a private variable in class.
void assignsomething()
{
string += "Blabla"; // Created a block of memory
string += " Blabla2"; // Added data again.
} // if I write a destructor that free heap with HeapDestroy() i can't use data in main()
int main()
{
assignsomething();
MessageBoxA(0,string,0,0);
// Byte.HeapFree();
}
Now… is it possible to set where destructor will be calling ?
or i should call free when i’m done with class ?
Thanks in advance.
Happy coding.
If you create it on the stack (you don’t create it via new) then the destructor will be called automatically when it goes out of scope. If you create it via new, you need to free it yourself by using operator delete when you’re done with it. Do NOT call free() on it, use the new and delete operators. Do not try to call the destructor by hand, just use delete
And yes, the destructor should release all dynamically allocated memory left in the class, unless you have a pointer to it outside the class. Try not to do that, it makes memory management hard and is generally considered bad design.