为什么C ++中需要析构函数? [英] Why are destructors required in C++?

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

问题描述

当指针超出范围,其内存被释放,为什么在c ++中创建析构函数

$ <$ p
< h2_lin>解决方案

如果你问为什么C ++类有析构函数,一些类有除了释放内存之外的需求。



此外,'unscoping'指针不会不是

em>>释放它指向的内存,因为其他指针可能正在引用它。



如果你有一个指针在堆栈上,退出函数将释放所使用的内存指针,但指针指向的内存。有一个微妙但非常重要的区别。


When a pointer goes out of scope, its memory is freed, so why are destructors created in c++?

解决方案

If you're asking why C++ classes have destructors, some classes have requirements other than just freeing memory. You may have an object that's allocated a socket connection that needs to be shut down cleanly, for example.

Also, 'unscoping' a pointer does not free the memory that it points to since other pointers may be referencing it.

If you have a pointer on the stack, exiting the function will free the memory used by the pointer but not that memory pointed to by the pointer. There's a subtle but very important distinction.

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

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