c++ - 将对象设置为 null 是否与 C++ 中的垃圾收集相同?
问题描述
我在这里有一个问题问我,如果将类的属性设置为 null 是否与在 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.
推荐阅读
- javascript - .map 不是带有 firestore 的 nextjs 上的函数错误
- javascript - 将 `:placeholder` 添加到 tailwind.config
- variables - 使用脚本任务在 SSIS 中发送多行输出
- python - 如何使用自定义 TclTk 安装从源代码构建 Python?
- openid-connect - Auth0 express-openid-connect 指定 IDP 与连接
- python - 在 Microsoft Graph API 中使用标题搜索电子邮件
- awk - 为什么我的 awk 脚本会创建空序列索引文件?
- awk - 如何使用 unix 实用程序 (sed/tr/awk) 用非转义等效项替换所有转义序列
- r - 使用 holtwinters 对测试数据进行提前预测
- node.js - 如何将主题添加到redis