zoukankan      html  css  js  c++  java
  • In p = new Fred(), does the Fred memory “leak” if the Fred constructor throws an exception?

    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 “Placement new” calls the Fred constructor. The pointer p becomes the this pointer inside the constructor, Fred::Fred().

  • 相关阅读:
    自制flash3D变换类
    Alchemy的使用和多项式批量计算的优化
    Bresenham直线扫描算法
    模拟流体粒子运动
    任意多边形的碰撞检测——向量积判断方法
    漂亮的雪花飘落和堆积效果
    发个简单怡情的粒子随机运动
    三次贝塞尔曲线绘制算法(优化过)
    失败是成功之母
    typeid操作符
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/5069971.html
Copyright © 2011-2022 走看看