Reputation: 581
Of course the next should not be done although it is valid for the compiler. But what is happening when you do?
CClass clss = *new CClass();
On the contrary to the above, the next does compile but gives an assertion error.
delete &clss;
Does this have something to do with allocating memory on either the stack or the heap?
Upvotes: 1
Views: 150
Reputation: 36391
The first line of code is correct, you initialize a statically allocated CClass
instance with an another instance dynamically allocated.
The second is obviously wrong as you try to delete an object that has not been dynamically allocated .
The first line produces a memory leak because you dynamically allocate a bunch of memory but never retain its address, so it can never be deallocated (deleted).
Upvotes: 1
Reputation: 65600
If you break it down:
new CClass()
-> dynamically-allocated instance pointer
CClass clss
-> statically-allocated variable
CClass clss = *new CClass();
-> copies the value pointed to by the temporary into clss
&clss
-> the address of a statically-allocated variable
delete &clss;
-> delete a statically-allocated variable (doesn't make sense)
Upvotes: 2