类析构函数的实际应用 [英] Practical application of class destructor

查看:111
本文介绍了类析构函数的实际应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正试图学习类和构造函数/析构函数。我明白这两个是做什么,但我有一个更难的时间与析构函数,因为我不能想到一个实际的应用程序使用。

I'm currently trying to learn about classes and constructors/destructors. I understand what the two do, but I'm having a harder time with the destructors because I can't think of a practical application for its use.

任何人都可以提供一个具有解释的示例?

Can anyone provide an example with an explanation?

推荐答案

析构函数是用于释放对象分配的任何资源的特殊成员函数。

Destructors are special member functions used to release any resources allocated by the object.

最常见的例子是类的构造函数使用 new ,析构函数使用 delete 以释放内存。

The most common example is when the constructor of the class uses new, and the destructor uses delete to deallocate the memory.

class Myclass
{
    int *m_ptr;
    public:
        Myclass():m_ptr(new int)
        {
        }
        ~Myclass()
        {
             delete m_ptr;
        }
        //ToDo: Follow Rule of Three
        //Provide definitions for copy constructor & copy assignment operator as well

};

这篇关于类析构函数的实际应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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