C++的拷贝构造,指针释放问题
黄舟
黄舟 2017-04-17 11:27:19
0
3
559

先上代码,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进行分配的内存进行释放?
我这样理解是否有错?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
迷茫

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();

巴扎黑

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

迷茫

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template