如果我删除一个类,它的成员变量是否自动删除? [英] If I delete a class, are its member variables automatically deleted?

查看:112
本文介绍了如果我删除一个类,它的成员变量是否自动删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究,没有相关的东西出现,所以我来了这里。



我试图避免内存泄漏,所以我想知道: p>

说我有类 MyClass with member int s a b int数组c 在成员函数中:

  class MyClass()
{
public:
int a ,b;
int [2] c;
void setVariables()
{
a,b = 0;
for(int i = 0; i <2; i ++)
{
c [i] = 3;
}
}
};
int main(int argc,char * argv)
{
MyClass * mc = new MyClass();
mc-> setVariables();
delete mc;
}

现在,我调用 delete mc a b c 也会被删除吗?或者我将在 MyClass

解决方案的析构函数中明确地执行p>当执行 delete mc 时,编译器调用对象的析构函数( MyClass ::〜MyClass() )然后释放与它相关的内存。



默认的析构函数(当你不声明自己的时候)调用所有成员变量的析构函数首先通过声明(即,在这种情况下, c ,然后 b ,然后 a )。由于此示例中的那些成员是 POD类型(它们没有析构函数),没有工作。


I have been researching, and nothing relevant has come up, so I came here.

I am trying to avoid memory leaks, so I am wondering:

Say I have class MyClass with member ints a and b, and an int array c, which are filled in a member function:

class MyClass()
{
    public:
        int a, b;
        int[2] c;
        void setVariables() 
        {
            a, b = 0;
            for (int i = 0; i < 2; i++) 
            {
                c[i] = 3;
            }
        }
};
int main(int argc, char* argv)
{
    MyClass* mc = new MyClass();
    mc->setVariables();
    delete mc;
} 

Now, after I call delete mc, will a, b, and all the contents of c be deleted as well? Or will I have to do that explicitly in the destructor of MyClass?

解决方案

When delete mc is executed, the compiler calls the destructor of the object (MyClass::~MyClass()) and then deallocates the memory associated with it.

The default destructor (when you don't declare your own) calls the destructors of all member variables, in order from last to first by declaration (that is, in this case, c, then b, then a). Since those members in this example are POD types (they do not have a destructor), no work is done.

这篇关于如果我删除一个类,它的成员变量是否自动删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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