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;  
}

运行结果与上方相同

注释

[编辑]
  1. ^ Finalize(),Finalize函数,英语:Finalizer

参考资料

[编辑]

相关条目

[编辑]
{{bottomLinkPreText}} {{bottomLinkText}}
析构函数
Listen to this article

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:

This article was just edited, click to reload
This article has been deleted on Wikipedia (Why?)

Back to homepage

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}}

Install Wikiwand

Install on Chrome Install on Firefox
Don't forget to rate us

Tell your friends about Wikiwand!

Gmail Facebook Twitter Link

Enjoying Wikiwand?

Tell your friends and spread the love:
Share on Gmail Share on Facebook Share on Twitter Share on Buffer

Our magic isn't perfect

You can help our automatic cover photo selection by reporting an unsuitable photo.

This photo is visually disturbing This photo is not a good choice

Thank you for helping!


Your input will affect cover photo selection, along with input from other users.

X

Get ready for Wikiwand 2.0 🎉! the new version arrives on September 1st! Don't want to wait?