Reputation: 1933
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 ?
Upvotes: 2
Views: 131
Reputation: 16876
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.
Upvotes: 7