Search code examples
c++pointersreferencedelete-operator

C++ delete operator with memory locations


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.


Solution

  •  T t = x;
    

    is known as Copy Initialization. It:

    • It tries to convert x to an object of type T &
    • Then copies over that object into the to-initialized object t.

    So your code statement,

    Point ppaa = *new Point;
    
    • Creates a Point obejct on freestore/heap and
    • then copies that object to create a stack object 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.