C ++ using * new class, lost pointer?

Curious why this fails. In the case where the object is returned and not the pointer itself to use the new one, why is it illegal to subsequently make a pointer, followed by deleting the pointer. Am I missing something in this sequence?

eg.

Example e = *new Example();      //dereferencing the pointer to get Example object
Example* g = &e;                 //pointer pointing to e address
delete g;                        //g is still pointer, but errors here.

      

+3


source to share


1 answer


C ++ pointers don't work exactly the same as Java references. Let it break.

Example e = *new Example();

      

This line creates an object Example

with dynamic storage duration, which is a fancy way of saying it makes an object somewhere in TM memory . Then you take that object that exists somewhere TM and copies it into a value with automatic storage duration. Now you have an object somewhere TM and a separate identical object stored on call stack 1 . The former was highlighted new

and the latter was not.

Example* g = &e;

      

Now you accept and declare g

as address e

. But it e

is on the stack, so it g

points to Example

one that was not allocated with new

.

delete g;

      



Then you try to delete g

, which points to an object with automatic storage duration. Hence the behavior is undefined.

As @ Rakete1111 mentioned in the comments, the behavior you are probably looking for is for C ++ reference types.

Example& e = *new Example();
Example* g = &e;
delete g;

      

This will declare e

as a referenced object, so it will point to the original one Example

in dynamic storage, while it looks and acts like a C ++ scanner. Then you can safely accept its address and remove it, getting the desired behavior. However, this is incredibly uniiomatic and probably shouldn't be used in real code.


1 Strictly speaking, the C ++ standard doesn't say anything about auto-holding objects on the call stack, but it can be useful to think of it this way for didactic purposes.

+5


source







All Articles