为什么C ++中需要析构函数? [英] Why are destructors required in C++?
问题描述
当指针超出范围,其内存被释放,为什么在c ++中创建析构函数
< h2_lin>解决方案
如果你问为什么C ++类有析构函数,一些类有除了释放内存之外的需求。
此外,'unscoping'指针不会不是
em>>释放它指向的内存,因为其他指针可能正在引用它。如果你有一个指针在堆栈上,退出函数将释放所使用的内存指针,但不指针指向的内存。有一个微妙但非常重要的区别。
When a pointer goes out of scope, its memory is freed, so why are destructor
s 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屋!