Curious as to why this fails. In the case where an object is returned rather than the pointer itself from using new, why is it illegal to make a pointer afterwards followed by deleting the pointer. Am I misunderstanding something with this sequence?
e.g.
Example e = *new Example(); //dereferencing the pointer to get Example object
Example* g = &e; //pointer pointing to e's address
delete g; //g is still pointer, but errors here.
C++ pointers don't work exactly like Java references. Let's break it down.
Example e = *new Example();
This line is constructing an Example object with dynamic storage duration, which is a fancy way of saying it's making an object somewhere in memoryTM. You're then taking that object that exists somewhereTM and copying it into a value with automatic storage duration. Now you have an object that's somewhereTM and a separate, identical object that's stored on the call stack1. The former was allocated with new, and the latter was not.
Example* g = &e;
Now you're taking and declaring g as the address of e. But e is on the stack, so g points to an Example that was not allocated using new.
delete g;
Then you try to delete g, which points to an object with automatic storage duration. Hence, undefined behavior.
As @Rakete1111 mentioned in the comments, the behavior you're probably looking for is with C++ reference types.
Example& e = *new Example();
Example* g = &e;
delete g;
This will declare e as a reference object, so that it points to the original Example in dynamic storage while looking and acting like a C++ scalar otherwise. Then you can safely take the address of it and delete it, getting the desired behavior. However, this is incredibly unidiomatic and should probably not be used in real code.
1 Strictly speaking, there's nothing in the C++ standard that says objects with automatic storage duration have to be on the call stack, but it can be helpful to think of it this way for didactic purposes.
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