所以我是一个试图掌握新运算符的初学者。我的析构函数有什么问题?
class arr{
public:
arr(){
pool=::operator new(100*sizeof(double));
}
~arr(){
::operator delete(pool);
}
void* pool;
};
int main()
{
arr a;
a.~arr(); //If I comment this out it's ok.
void* pool2=::operator new(100*sizeof(double)); //Works
::operator delete(pool2); //Fine.
system("pause");
return 0;
}
离开a.~arr();在给我这个错误:
调试断言失败!文件:dbgdel.cpp 行:52
表达式:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
我不明白为什么 pool2 工作正常,但使用这个类给我带来了问题。此外,错误仅在系统“暂停”后弹出,即在调用 a.~arr() 之后???
谢谢!
最佳答案
好吧,乍一看,您不应该显式调用析构函数。而是使用范围来强制超出范围并调用析构函数。
int main()
{
{
arr a;
} //This calls destructor of a
//Rest of code
}
否则,a 的析构函数会被调用两次:一次是在您调用它时,另一次是在 a 超出范围时。
编辑:
给你。
关于c++ - 运算符 new/delete 和析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4737403/