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

发布于 2024-11-13 09:52:26 字数 700 浏览 4 评论 0原文

我一直在研究,没有任何相关的结果,所以我来到这里。

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

假设我有类 MyClass ,其中成员 ints ab< /code> 和一个 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;
} 

现在,在我调用 delete mc 后,将 ab,以及所有内容c 也被删除吗?或者我是否必须在 MyClass 的析构函数中显式地执行此操作?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

半夏半凉 2024-11-20 09:52:26

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

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

The rule is very simple: every object created with new must 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 mc after creating it with new, and not deleting the members which were not created with 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 new to initialise a smart pointer to manage the object for you.

茶花眉 2024-11-20 09:52:26

当执行delete mc时,编译器调用对象的析构函数(MyClass::~MyClass()),然后释放与其关联的内存。

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

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.

方圜几里 2024-11-20 09:52:26

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

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

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

有关类内存消耗的更多信息:

C++ 类

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, BUT the memory they point at isn't destroyed.

More about class memory consumption:

C++ Classes

我很坚强 2024-11-20 09:52:26

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

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.

趴在窗边数星星i 2024-11-20 09:52:26

对于您的具体示例,答案是肯定的。那是因为你在堆栈上分配了成员变量。如果您使用 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;          
     }     
   } 


} 

For your specific example, the answer is yes. That's because you allocated the member variables on the stack. If you had used new to 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.

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;          
     }     
   } 


} 
人间不值得 2024-11-20 09:52:26

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

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

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.

甜柠檬 2024-11-20 09:52:26

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

至于你的具体问题:

调用delete mc后,a、b、c的内容会被删除吗?或者我必须在 MyClass 的析构函数中显式地执行此操作?

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

delete will 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.

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?

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

汹涌人海 2024-11-20 09:52:26

您的三个变量没有使用 new 分配,因此根本不需要删除它们。

当您的类被删除时,它们被破坏(因为它们是在您的类被新建时分配的),但这与正在被删除。

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文