If I delete a class, are its member variables auto

2019-01-21 23:44发布

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 c[2];
        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?

8条回答
爷的心禁止访问
2楼-- · 2019-01-22 00:04

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.

查看更多
祖国的老花朵
3楼-- · 2019-01-22 00:04

When you free an object, all of its member variables are automatically freed as well. So, in your case, yes, a, b and c are all freed.

However, if one of your member variables is a pointer, only the pointer itself is automatically freed, not the object it points to - this is the most common case for having to write your own destructor.

查看更多
登录 后发表回答