c++ - 为什么在取消引用/释放动态创建的对象之后,它仍然在 C++ 中被引用?
问题描述
#include<iostream>
#include<conio.h>
using namespace std;
class Marie{
public:
int x;
Marie(){
cout<<"created";
}
~Marie(){
cout<<"hii i am destructor";
}
void ShowMarie() {
cout<<"friends";
x=5;
delete this; /*<--- here destructor called */
}
};
int main(){
Marie *ptr = new Marie;
ptr->ShowMarie();
cout<<ptr->x; /*<---- ptr is dangling pointer but it is still showing me the correct value.*/
getch();
}
- 调用对象的析构函数后,它仍然像在内存中一样引用吗?为什么?
- 为什么我们需要为动态创建的对象显式调用析构函数
delete this
呢? - 如果我们使用
delete this;
内部析构函数会发生什么?这是递归调用析构函数吗?
解决方案
调用对象的析构函数后,它仍然像在内存中一样引用吗?为什么?
删除指针不会将任何内存清零,因为这样做会占用 CPU 周期,而这不是 C++ 的意义所在。你所拥有的是一个悬空指针,并且可能是一个微妙的错误......(Benj回答)。
为什么我们需要使用 delete this 为动态创建的对象显式调用析构函数?
如果对象是使用运算符 new() 的重载形式构造的,则需要手动调用析构函数,除非使用“std::nothrow”重载......(Dietmar Kühl回答)。
如果我们使用删除这个;在析构函数里面会发生什么?这是递归调用析构函数吗?
一旦调用析构函数(第一次),对象的生命周期就结束了。因此,如果您从析构函数中调用对象的析构函数,则行为未定义......(James McNellis回答)。
请在您未来的搜索中使用 stackoverflow 数据库,大多数时候您的问题已经有了答案。
推荐阅读
- python - “餐厅”对象没有属性“添加服务”
- firefox - AES GCM 仅解密 Firefox 错误:“DOMException: The operation failed for an operation-specific reason”,但 Chromium OK
- pact-broker - 如何为自托管的契约代理创建 webhook?
- android - 使用私有子模块发布到 MavenCentral
- excel - Excel 超动态范围与 OFFSET(...COLUMN()) 转换为非易失性
- python - 每当添加这两个特定的代码行时,Python 都会跳过第一个 if 条件
- postgresql - 带有本机查询 Java Entity Manager 的 Postgres Ltree 扩展
- excel - 如何将 VBA 嵌套字典保存到 Excel 单元格?
- botframework - 附件预览在 Microsoft Teams 中不起作用:Bot 框架 v4
- mysql - 在 3 个表中使用匹配优化查询。mysql