博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
In p = new Fred(), does the Fred memory “leak” if the Fred constructor throws an exception?
阅读量:4677 次
发布时间:2019-06-09

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

No.

If an exception occurs during the Fred constructor of p = new Fred(), the C++ language guarantees that the memory sizeof(Fred) bytes that were allocated will automagically be released back to the heap.

Here are the details: new Fred() is a two-step process:

  1. sizeof(Fred) bytes of memory are allocated using the primitive void* operator new(size_t nbytes). This primitive is similar in spirit to malloc(size_t nbytes). (Note, however, that these two are not interchangeable; e.g., there is no guarantee that the two memory allocation primitives even use the same heap!).
  2. It constructs an object in that memory by calling the Fred constructor. The pointer returned from the first step is passed as the this parameter to the constructor. This step is wrapped in a trycatch block to handle the case when an exception is thrown during this step.

Thus the actual generated code is functionally similar to:

  1. // Original code: Fred* p = new Fred();
  2. Fred* p;
  3. void* tmp = operator new(sizeof(Fred));
  4. try {
  5. new(tmp) Fred(); // Placement new
  6. p = (Fred*)tmp; // The pointer is assigned only if the ctor succeeds
  7. }
  8. catch (...) {
  9. operator delete(tmp); // Deallocate the memory
  10. throw; // Re-throw the exception
  11. }

The statement marked “” calls the Fred constructor. The pointer p becomes the this pointer inside the constructor, Fred::Fred().

转载于:https://www.cnblogs.com/hustxujinkang/p/5069971.html

你可能感兴趣的文章
决策树
查看>>
团队作业
查看>>
如何避免在简单业务逻辑上面的细节上面出错
查看>>
大型网站高并发的架构演变图-摘自网络
查看>>
8丶运行及总结
查看>>
[洛谷P4234]最小差值生成树
查看>>
redis安装配置
查看>>
结对项目博客
查看>>
讨论记录:求大于一个时间段的最大平均积分,O(n)时间实现
查看>>
error) DENIED Redis is running in protected mode because protected mode is enabled报错
查看>>
CSS-16-margin值重叠问题
查看>>
selenium常用方法
查看>>
第二次作业
查看>>
ios 面试题
查看>>
MySQL教程(二)—— 关于在ACCESS中使用SQL语句
查看>>
实验4.1
查看>>
接口Interface
查看>>
bzoj 1651: [Usaco2006 Feb]Stall Reservations 专用牛棚【贪心+堆||差分】
查看>>
bzoj 1710: [Usaco2007 Open]Cheappal 廉价回文【区间dp】
查看>>
电商:购物车模块解决思路
查看>>