简体   繁体   中英

Understanding delete in C++ with

I have following code snippet from a C++ book I am reading.

int* operator=(const int& rhs, int *x)
{
   int *tmpx=x              //line 1
   x = new int(2)           //line 2 
   delete tmpx;             //line 3
   return x;                //line 4                   
}

My doubt is that If I am deleting tmpx on line 3 which holds the address to memory location that x points to, and deleting will invalidate the memory address, So wouldn't it be wrong to return x which is pointing to memory address that was freed at line 3 ?

No, it's right. Because here you're assigning a new value to x .

x= new int(2);           //line 2

So now tmpx and x point to different places. tmpx points to the old x .

delete tmpx;             //line 3

Here you're deleting tmpx , which doesn't affect x , which is now pointing to the new position.

return x;                //line 4  

You're returning the address of x that was returned by new in this function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM