我怎么称呼该类的析构函数? [英] How do I call the class's destructor?

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

问题描述

我有一个简单的C ++代码,但是我不知道如何使用析构函数:

I have a simple C++ code, but I don't know how to use the destructor:

class date {

public:
    int day;
    date(int m)
    {
        day =m;
    }

    ~date(){
    cout << "I wish you have entered the year \n" << day;    
    }
};


int main()
{
  date ob2(12);
  ob2.~date();
  cout << ob2.day;
  return 0;
}

我的问题是,我应该写些什么?析构函数代码,调用析构函数后,它将删除 day 变量

The question that I have is, what should I write in my destructor code, that after calling the destructor, it will delete the day variable?

推荐答案

您不应显式调用析构函数。

You should not call your destructor explicitly.

在堆栈上创建对象时(如您所做的那样),您需要做的是:

When you create your object on the stack (like you did) all you need is:

int main()
{
  date ob2(12);
  // ob2.day holds 12
  return 0; // ob2's destructor will get called here, after which it's memory is freed
}

何时您在堆上创建对象,还需要 delete 您的类,然后调用其析构函数并释放内存:

When you create your object on the heap, you kinda need to delete your class before its destructor is called and memory is freed:

int main()
{
  date* ob2 = new date(12);
  // ob2->day holds 12
  delete ob2; // ob2's destructor will get called here, after which it's memory is freed
  return 0;   // ob2 is invalid at this point.
}

(在最后一个示例中未能调用delete会导致内存丢失。)

(Failing to call delete on this last example will result in memory loss.)

两种方法都有其优点和缺点。堆栈的方式非常快,可以分配对象将要占用的内存,并且您无需显式删除它,但是堆栈的空间有限,您无法轻松,快速,干净地移动这些对象。

Both ways have their advantages and disadvantages. The stack way is VERY fast with allocating the memory the object will occupy and you do not need to explicitly delete it, but the stack has limited space and you cannot move those objects around easily, fast and cleanly.

首选的方法是使用堆,但是在性能方面,分配速度很慢,您必须处理指针。但是,您在处理对象时拥有更大的灵活性,可以更快地进一步处理指针,并且可以更好地控制对象的生命周期。

The heap is the preferred way of doing it, but when it comes to performance it is slow to allocate and you have to deal with pointers. But you have much more flexibility with what you do with your object, it's way faster to work with pointers further and you have more control over the object's lifetime.

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

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