本文介绍了如何手动销毁成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对析构函数有一个基本问题。

I have a basic question on destructors.

假设我有以下课程

class A
{
public:

int z;
int* ptr;

A(){z=5 ; ptr = new int[3]; } ;
~A() {delete[] ptr;};

}

现在,析构函数应该破坏对象的实例化。
上面的析构函数正是这样做的,它释放了new分配的动态分配的内存。

Now destructors are supposed to destroy an instantiation of an object.The destructor above does exactly that, in freeing the dynamically alloctaed memory allocated by new.

但是变量 z 呢?我应该如何手动销毁它/释放 z 分配的内存?类超出范围时会自动销毁吗?

But what about the variable z? How should I manually destroy it / free the memory allocated by z? Does it get destroyed automatically when the class goes out of scope?

推荐答案

它会自动销毁,尽管在您的示例中是 int z 是POD类型的,没有显式的析构函数...只是简单地回收了内存。否则,如果该对象有一个析构函数,则将调用该函数以在主类 A 已完成,但尚未退出。

It gets "destroyed" automatically, although since in your example int z is a POD-type, there is no explicit destructor ... the memory is simply reclaimed. Otherwise, if there was a destructor for the object, it would be called to properly clean-up the resources of that non-static data member after the body of the destructor for the main class A had completed, but not exited.

这篇关于如何手动销毁成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:49