博客
关于我
delete对象时会自动调用类的析构函数
阅读量:416 次
发布时间:2019-03-06

本文共 580 字,大约阅读时间需要 1 分钟。

背景

在C++编程中,对象结束其生命周期时,系统会自动调用析构函数(Destructor).当类中包含动态分配的内存时,析构函数会负责释放这些动态分配的内存。然而,长期以来,我一直对delete操作和析构函数之间的关系并没有深入了解。最近在学习delete相关知识时,我发现了一段有趣的描述:

举例

以下代码展示了两种情况:

如果 #if 1

// 代码片段Test *t = new Test();t->p = new char[10];strcpy(t->p, "hello");delete t;

运行结果会显示:

  • "Object Release" 被打印
  • "p Release" 也被打印

这表明,在执行delete操作后,系统立即调用了析构函数。

如果 #else

// 代码片段Test t;t.p = new char[10];strcpy(t.p, "hello");

在这种情况下,对象t是栈内存中的,因此不会使用delete操作.相反,当main函数结束时,系统会自动调用析构函数,释放内存.

总结

通过这两个例子可以看出,在栈中创建的对象和堆中创建的对象在内存释放上有显著的不同.堆中的对象需要手动调用delete,而栈中的对象则由系统自动释放.这种差异反映了内存管理的两种不同的方式,在编写高效和安全的C++代码时需要充分理解这些差异.

转载地址:http://qnbkz.baihongyu.com/

你可能感兴趣的文章
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
Orleans框架------基于Actor模型生成分布式Id
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>
ORM sqlachemy学习
查看>>
Ormlite数据库
查看>>
orm总结
查看>>