3

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.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
noclew
  • 542
  • 2
  • 5
  • 13
  • You're leaking memory. This may help: http://stackoverflow.com/questions/8839943/why-does-the-use-of-new-cause-memory-leaks/8840302 – Pubby Nov 03 '12 at 05:09
  • Thank Pubbu, it helped a lot. Could you please look into the additional question posted under the Als's answer? – noclew Nov 03 '12 at 06:17

1 Answers1

3
 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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • Thanks very much for your kind explanation. Now I can see how things work in my code! I used c# for a while, so this Copy Initialization is quite interesting to me. Just to be clear, if I write like this in c#(not in c++) : T t1 = new T(); T t2 = t1; then t2 is just a reference of t1, and there is no copying process as in c++. Am I right? – noclew Nov 03 '12 at 05:43