0

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!

Yíu
  • 383
  • 3
  • 14
  • 2
    Use `std::string` and let the standard library implementation handle the memory management for you. – NathanOliver Oct 28 '16 at 18:34
  • @NathanOliver Unfortunately not possible since this is for an assignement and there are some things I am not allowed to change, such as the type of `name_` being `char*`. – Yíu Oct 28 '16 at 18:36

1 Answers1

1

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67