use*_*596 3 c++ exception-handling
我坚持使用我的析构函数我的简短代码结构是这样的
class test
{
private:
string code;
int digit, num_digit;
//destructor
~test()
{
if(digit >= 0 && digit > num_digit)
{
for(unsigned int i=0; i<code.length(); i++) delete &code[i];
}
}
};
<more code> .............
<more code> .............
int main()
{
Test test1
test1.~test();
}
Run Code Online (Sandbox Code Playgroud)
在浏览析构函数时,我的核心会中止.Unix编译器说Aborted - 'core dumped'有什么想法吗?
中止正在发生,因为正在尝试对delete未动态分配的对象:仅delete通过new(和delete[]for new[])创建的对象.该code成员未动态分配.当包含对象被销毁时,它将被自动销毁.在Test没有理由手工编写析构函数的情况下.
这是不正确的:
test1.~test();
Run Code Online (Sandbox Code Playgroud)
不要显式调用对象的析构函数.test1超出范围时,将自动调用析构函数.对于动态分配的对象,析构函数将在deleted 时调用.