我想消除一些乱码的所有内存泄漏。我有一个类Employee
与被堆上了new *char
运行期间分配的成员name_
。现在有些例子name_
在Employee
的析构函数被调用之前被手动删除。我知道这是不好的做法。但是,在某些情况下,我仍然需要通过析构函数删除name_
。我试过的东西根据是否有空闲空间,我可以释放内存吗?
Employee::~Employee(){
if (this->name_)
{
delete[] this->name_;
}
}
或
if (this->name_ != NULL)
{
delete[] this->name_;
}
或
if (this->name_[0] != '\0')
{
delete[] this->name_;
}
不过那些没有意识到name_
已经delted别的地方,试图删除一些东西,也没存在了。
所以,我需要这样的东西
if (char* name_ not deleted yet)
{
delte name_
}
有没有一种方法来检查withing的if
天气成员已被删除?
编辑: 感谢您的链接到已经回答了我的问题,的确如此!
使用'的std :: string',让标准库的实现处理内存管理你。 – NathanOliver
@NathanOliver不幸的是不可能的,因为这是一个assignement,有一些我不允许改变,比如'name_'的类型是'char *'。 –