C++ 如果我删除一个类,它的成员变量会自动删除吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6256492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:47:15  来源:igfitidea点击:

If I delete a class, are its member variables automatically deleted?

c++classvariablesmemberdelete-operator

提问by Keelx

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 MyClasswith member ints aand b, and an int array c, which are filled in a member function:

假设我有一个MyClass包含成员intsab和 an 的类int array c,它们填充了一个成员函数:

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 cbe deleted as well? Or will I have to do that explicitly in the destructor of MyClass?

现在,我打电话后delete mc,会ab以及所有的内容c被删除?或者我必须在 的析构函数中明确地这样做MyClass吗?

回答by Mike Seymour

The rule is very simple: every object created with newmust be destroyed exactly once with delete; every array created with new[]must be destroyed exactly once with delete[]; everything else must not be deleted. So your code is correct; you are deleting mcafter creating it with new, and not deleting the members which were not created with new.

规则很简单:每个用创建的对象都new必须用 销毁一次delete;每个用 with 创建的数组都new[]必须用 销毁一次delete[];不得删除其他所有内容。所以你的代码是正确的;您mc在使用 . 创建它后删除new,而不是删除不是用new.创建的成员。

Applying the rule can be quite tricky when the program flow gets complicated (especially when exceptions are involved); for that reason, it is much better not to delete objects yourself, but to immediately use the result of newto initialise a smart pointer to manage the object for you.

当程序流程变得复杂时(尤其是在涉及异常时),应用规则可能会非常棘手;因此,最好不要自己删除对象,而是立即使用 的结果new来初始化智能指针来为您管理对象。

回答by greyfade

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

delete mc被执行时,编译器调用所述对象(的析构函数MyClass::~MyClass()),然后将释放与它相关的存储器中。

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.

默认析构函数(当您不声明自己的时)调用所有成员变量的析构函数,按照从最后到第一个声明的顺序(即,在这种情况下,c, then b, then a)。由于本示例中的那些成员是POD 类型(它们没有析构函数),因此没有完成任何工作。

回答by Yochai Timmer

Class members are a part of the class' memory structure.

类成员是类内存结构的一部分。

So when you free that memory, the members are freed with it.

因此,当您释放该内存时,成员也随之释放。

NOTE:
If you have pointers they are destroyed too, BUTthe memory they point at isn't destroyed.

注意:
如果您有指针,它们也会被销毁,它们指向的内存不会被销毁。

More about class memory consumption:

更多关于类内存消耗:

C++ Classes

C++ 类

回答by nathan

For your specific example, the answer is yes. That's because you allocated the member variables on the stack. If you had used newto allocate memory for the member variables the answer would be no and would require you to explicitly delete the member variables in the class' destructor.

对于您的具体示例,答案是肯定的。那是因为您在堆栈上分配了成员变量。如果您曾经new为成员变量分配内存,则答案是否定的,并且需要您显式删除类的析构函数中的成员变量。

class MyClass(): heapVariabl(NULL)
{  
   MyClass()
   {}

   ~MyClass()
   {
     delete heapVariable; 
   }   

   int a, b;     
   int[2] c;     
   int *heapVariable;
   void setVariables()      
   {         
     a, b = 0;       
     heapVariable = new int; // <- requires deletion in destructor to free memory
     *heapVariable = 0;
     for (int i = 0; i < 2; i++)          
     {             
       c[i] = 3;          
     }     
   } 


} 

回答by wanovak

Variables inside of a class have class scope and are destroyed when the class is. The only thing you need to worry about is pointers -- those will need to be addressed appropriately in your destructor.

类内的变量具有类作用域,并在类存在时销毁。您唯一需要担心的是指针——它们需要在您的析构函数中适当地解决。

回答by HighCommander4

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

当您释放一个对象时,它的所有成员变量也会自动释放。所以,在你的情况下,是的abc都被释放了。

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

但是,如果您的成员变量之一是指针,则只会自动释放指针本身,而不是它指向的对象 - 这是必须编写自己的析构函数的最常见情况。

回答by Ed S.

deletewill reclaim the memory that your object contains. If your type maintains pointers to dynamically allocated memory then you will need to clean those up inside of your destructor.

delete将回收您的对象包含的内存。如果您的类型维护指向动态分配的内存的指针,那么您将需要在析构函数内部清理它们。

As for your specific quesiton:

至于你的具体问题:

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?

调用delete mc后,a、b、c的所有内容都会被删除吗?或者我必须在 MyClass 的析构函数中明确地这样做吗?

They will be cleaned up for you as they were not allocated dynamically.

由于它们不是动态分配的,因此将为您清理它们。

回答by Mark B

Your three variables were not allocated with newso there would be no need to delete them at all.

你的三个变量没有分配,new所以根本不需要删除它们。

They wouldbe destructed when your class is deleted (as they were allocated when your class was newd), but that's not the same as being deleted.

当您的班级为d时,它们被破坏delete(因为它们在您的班级为newd时被分配),但这与被删除不同。