析构函数不是为什么? [英] Destructor is not calling why ?

查看:102
本文介绍了析构函数不是为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  class  
B

{

B()

{

}

~B()

{

printf(" B des"
);< br />

}

};

$
class
A
$
{

B * b;

A()

{

b = new
B();

}

¥ b $ b~A()

{

如果
(b)

免费(b);

}



}

$
class
C

{

A * a;

C()

{

a = new
A();

}

~C()

{

如果
(a)

免费A;

}



}





main()

{

C c;

}



<这是一个C ++问题,不属于XPS论坛。


然而,没有调用析构函数的原因是你使用的是"free"。你应该使用"删除"代替。这将调用适当的析构函数,然后释放由"new"分配的内存。只应使用
free()释放使用malloc()分配的内存。


class
 B
{
B()
{
}
~B()
{
printf(" B des" );<br/>
}
};

class A
{
B *b;
A()
{
b = new B();
}

~A()
{
if (b)
free(b);
}

}

class C
{
A *a;
C()
{
a = new A();
}
~C()
{
if (a)
free A;
}

}


main()
{
C c;
}

解决方案

This is a C++ question and does not belong to the XPS forum.

Nevertheless, the reason the destructor is not called is you are using "free". You should use "delete" instead. That will call the appropriate destructor and then free the memory allocated by "new". Only memory allocated using malloc() should be freed using free().


这篇关于析构函数不是为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆