Yíu Yíu - 1 month ago 12
C++ Question

Can I free memory depending on if there is something to free?

I am trying to eliminate all memory leaks from some messy code. I have a class

Employee
with the member
name_
which gets allocated on the heap with a
new *char
during runtime. Now there are some instances where
name_
gets deleted manually before
Employee
's destructor gets called. I know this is bad practice. However, there are some cases where I still need
name_
to be deleted through the destructor. I tried things like

Employee::~Employee(){
if (this->name_)
{
delete[] this->name_;
}
}


or

if (this->name_ != NULL)
{
delete[] this->name_;
}


or

if (this->name_[0] != '\0')
{
delete[] this->name_;
}


But those options didn't realize
name_
has already been delted somewhere else and tried to delete something which didn't exist anymore.

So I would need something like

if (char* name_ not deleted yet)
{
delte name_
}


Is there a way to check withing an
if
weather a member has already been deleted?

Edit:
Thanks for the link to the question that already answered mine, indeed it does!

Answer

If you insist on managing memory for name_ manually (instead of using std::string), you can simply encapsulate it into your class and delete it manually via some reset() function that sets name_ to nullptr after deleting it. Then in your destructor, you simply check if name_ is not nullptr and delete it.

Comments