For faster navigation, this Iframe is preloading the Wikiwand page for
析构函数.
析构函数(英语:Destructor,有时简称 dtor)在面向对象程式设计里是一个方法,当对象的生命周期结束时,它会自动地被调用执行。它最主要的目的在于,清空并释放物件先前建立或是占用的存储器资源。析构函数的整体使用概念关键在于RAII。一个具备垃圾回收机制的编程语言,无法确保析构函数是否会被执行,通常这类的编程语言不属于RAII的范围内。这类的编程语言,只要经由某个适当的函数,通常会调用Dispose()
函数,做调用的动作,那么它一定会从现有资源释放物件。与使用垃圾回收机制的Finalize()
相比,建议使用析构函数是释放资源的适当做法[注 1]。
class Demo{
public:
~Demo() //定义析构函数
{
std::cout << "调用了析构函数 " << std::endl;
}
};
int main()
{
{
Demo demo ;
} // 在部分开发环境中可能没有显示内容,把它放在块儿中即可
return 0; //返回之前调用析构函数;
}
运行结果为:
调用了析构函数
第二种调用方式:
class Demo{
public:
~Demo() //定义析构函数
{
std::cout << "调用了析构函数 " << std::endl;
}
};
int main()
{
Demo(); //在Visual Studio 2017中运行。
return 0;
}
运行结果与上方相同
{{bottomLinkPreText}}
{{bottomLinkText}}
This page is based on a Wikipedia article written by
contributors (read/edit).
Text is available under the
CC BY-SA 4.0 license; additional terms may apply.
Images, videos and audio are available under their respective licenses.
{{current.index+1}} of {{items.length}}
Thanks for reporting this video!
This browser is not supported by Wikiwand :(
Wikiwand requires a browser with modern capabilities in order to provide you with the best reading experience.
Please download and use one of the following browsers:
An extension you use may be preventing Wikiwand articles from loading properly.
If you're using HTTPS Everywhere or you're unable to access any article on Wikiwand, please consider switching to HTTPS (https://www.wikiwand.com).
An extension you use may be preventing Wikiwand articles from loading properly.
If you are using an Ad-Blocker, it might have mistakenly blocked our content.
You will need to temporarily disable your Ad-blocker to view this page.
✕
This article was just edited, click to reload
Please click Add in the dialog above
Please click Allow in the top-left corner,
then click Install Now in the dialog
Please click Open in the download dialog,
then click Install
Please click the "Downloads" icon in the Safari toolbar, open the first download in the list,
then click Install
{{::$root.activation.text}}
Follow Us
Don't forget to rate us
Oh no, there's been an error
Please help us solve this error by emailing us at
support@wikiwand.com
Let us know what you've done that caused this error, what browser you're using, and whether you have any special extensions/add-ons installed.
Thank you!