我对析构函数有一些疑问.
class cls
{
char *ch;
public:
cls(const char* _ch)
{
cout<<"\nconstructor called";
ch = new char[strlen(_ch)];
strcpy(ch,_ch);
}
~cls()
{
//will this destructor automatically delete char array ch on heap?
//delete[] ch; including this is throwing heap corruption error
}
void operator delete(void* ptr)
{
cout<<"\noperator delete called";
free(ptr);
}
};
int main()
{
cls* cs = new cls("hello!");
delete(cs);
getchar();
}
另外,由于析构函数会在删除时自动调用,为什么在所有逻辑都可以在析构函数中编写时我们需要显式删除?
我对运算符删除和析构函数非常困惑,无法确定其具体用法.精心描述将非常有用.
编辑:
我的理解基于答案:
对于这种特殊情况,默认的析构函数会破坏char指针,因此我们需要先显式删除char数组,否则会导致内存泄漏.如果我错了,请纠正我.
解决方法
好吧,默认的析构函数释放成员变量使用的内存(即成员指针ch本身不再存在),但它不会自动释放成员指针引用的任何内存.因此,您的示例中存在内存泄漏.