In p = new Fred(), does the Fred memory “leak” if the Fred constructor throws an exception?
2015-12-23 14:58
477 查看
No.
If an exception occurs during the
Here are the details:
It constructs an object in that memory by calling the
Thus the actual generated code is functionally similar to:
The statement marked “Placement
If an exception occurs during the
Fredconstructor 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:
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!).
It constructs an object in that memory by calling the
Fredconstructor. The pointer returned from the first step is passed as the
thisparameter to the constructor. This step is wrapped in a
try…
catchblock to handle the case when an exception is thrown during this step.
Thus the actual generated code is functionally similar to:
// Original code: Fred* p = new Fred();
Fred* p;
void* tmp = operator new(sizeof(Fred));
try {
new(tmp) Fred(); // Placement new
p = (Fred*)tmp; // The pointer is assigned only if the ctor succeeds
}
catch (...) {
operator delete(tmp); // Deallocate the memory
throw; // Re-throw the exception
}
The statement marked “Placement
new” calls the
Fredconstructor. The pointer
pbecomes the
thispointer inside the constructor,
Fred::Fred().
相关文章推荐
- 初识GoAhead
- udev
- 第二章 身份验证
- 自旋锁、排队自旋锁、MCS锁、CLH锁
- Mysql JDBC 连接串参数说明
- 设计模式C++实现--建造者模式
- Mybatis和hibernate比较
- 2015年第21本:万万没想到,用理工科思维理解世界
- JS模拟土豆弹窗——链式运动
- 自动回填 - 报表系统
- Hadoop 单节点 & 伪分布 安装手记
- 进程结构和内存布局
- 每天一个linux之touch命令
- 程序崩溃问题-[UIApplication _runWithMainScene:transitionContext:completion:]
- Android 中 SystemProperties 使用方法
- Unity3d打包发布Android程序
- kx项目总结
- bzoj2819 Nim
- 3D触控简介:建立数字刻度应用及快速活动栏
- CC2540串口使用小心得