I am new to C++, and now am studying new and delete keywords.
Point ppaa = *new Point;
Point *p = &ppaa;
ppaa.xpos = 1;
ppaa.ypos= 3;
delete &ppaa;
delete p;
Could you please explain why I cannot delete the ppaa above using &ppaa? I know that delete can only operate on pointer, but I cannot understand why above is not possible since they are actually memory locations. Searching similar questions, it seems that this is related to the copying operations that happen at the first line, but I do not have good explanations.
T t = x;
is known as Copy Initialization. It:
x to an object of type T & t.So your code statement,
Point ppaa = *new Point;
Point obejct on freestore/heap and ppaa.Both these objects are different objects.
As you can see, You do not have any pointer to the heap object anymore after executing this statement.
You need to pass the address returned by new to delete in this case, Since you do not have the address anymore it results in memory leak.
Further, Note that &ppaa does not return the address returned by new it returns the address of the object ppaa located on the stack. Passing this address to delete results in Undefined Behavior because ppaa was never allocated on freestore/dynamically it is a stack based local/automatic object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With