C ++析构函数。如何手动销毁成员变量 [英] C++ destructors. How to manually destroy member variables
问题描述
我有一个关于析构函数的基本问题。
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.
这篇关于C ++析构函数。如何手动销毁成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!