首页 > 解决方案 > 将对象设置为 null 是否与 C++ 中的垃圾收集相同?

问题描述

我在这里有一个问题问我,如果将类的属性设置为 null 是否与在 c++ 中收集垃圾相同。以及这与内存管理有何关系。谢谢

标签: c++

解决方案


C++ 中没有垃圾收集。如果您不释放内存,它将不会被释放。一旦一个对象被销毁,但是所有成员对象也被销毁,但是指针不是它们指向的对象,因此必须手动销毁这些对象。对于您的问题:如果您将某些内容设置为 NULL,则该值将变为 NULL,但该对象将保留。

例子:

struct A {
    int a;
    int* b;
};

void func(){
    // Create a stack allocated variable
    A stack_allocated = {5, new int(5)};
    // Create a heap allocated variable
    A* heap_allocated = new A({5,new int(5)});
} // Upon exiting stack_allocated is destroyed, but heap_allocated is not.
// It is also important to note that stack_allocated.b is not destroyed only
// the pointer to it. Use delete to get rid of those.

推荐阅读