Home  >  Q&A  >  body text

C++的拷贝构造,指针释放问题

先上代码,no code no say

/*
class Point{
//...
};
*/
Point *pPoint = new Point;    //1
Point point;                  //2                
*pPoint = point;              //3
//...
delete pPoint                 //4

关于步骤1new可分解为如下:

//cpp为代码
Point *pPoint = __new( sizeof(Point));   //5
if(pPoint)
{
    pPoint->Point::Point();
}

步骤3,是不是就是调用Point的拷贝赋值函数?
步骤4删除该指针就是针对步骤5进行分配的内存进行释放?
我这样理解是否有错?

黄舟黄舟2764 days ago557

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-17 11:29:19

    The understanding of step 3 is basically correct. Step 4 not only releases the memory, but also executes the destructor before that, which is basically equivalent to pPoint->Point::~Point();

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 11:29:19

    Excuse me, after executing step 5, isn’t this memory still not released?

    reply
    0
  • 迷茫

    迷茫2017-04-17 11:29:19

    There is no problem in understanding step 3, and there is no problem in step 4, but pPoint = NULL should be added. Because your delete just tells the program that I don't want this pointer anymore. After the memory is released, the pointer still points to that memory, which may cause problems.

    reply
    0
  • Cancelreply