如何正确定义析构函数 [英] How to properly define destructor

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

问题描述

我对C ++(和一般的编程)相对来说是新的,所以请谅解,如果问题不是立即完全清除。

I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.

我有一个程序其中创建了一定数量的内部定义类(让我们称之为class1)的对象。
程序工作完美,对象做他们应该做的。

What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created. The program works perfectly fine and the objects do what they should.

我目前想解决的问题是以下:这些对象不会被销毁

The problem that I am currently trying to solve is the following: these objects are not destroyed (and thus memory is not de-allocated) until the program exits, but I need that memory earlier.

在类的其他成员中有其他内部的对象(也有成员是第三个类的对象)。

Among the other members of the class there are objects of other internally defined classes (who also have members that are objects of a third class).

我的问题是如何正确定义一个析构函数的对象class1 ,以便所有的数据被取消,内存释放?

My question is the following: how do I properly define a destructor for the objects of "class1" so that all the data is cancelled and the memory deallocated?

我发现(可能这是很明显的已经)一个析构函数像

I found out (probably this was obvious for you already) that a destructor like

class1::~class1(void) {

}

不会工作(我为所有内部定义的类定义了类似的析构函数)。

won't work (I defined similar destructors for all internally defined classes).

我的错误可能是,这是一个析构函数,什么都不做。如何解决这个问题?

Reading around I understood that my mistake could be that that is a destructor that does nothing. How do I solve this?

感谢任何人回答/帮助/评论。

Thanks to anyone who will answer/help/comment.

Federico


Federico

推荐答案

在C ++中,您需要手动释放内存。没有垃圾回收器。你显然需要在你的析构函数中手动释放内存。如果您使用分配内存,您需要使用解除构造函数中 new 分配的每个资源 ,例如:

In C++ you need to free the memory manually. There's no garbage collector. You obviously need to free the memory manually inside your destructor. If you allocated the memory using new, you need to use delete for each resource you allocated with new inside the deconstructor, for example:

class1::~class1(void)
{
    delete resource1;
    delete resource2;
    etc...
}

这篇关于如何正确定义析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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