If I have the following piece of code:
int *q = new int(42), *r = new int(100);
r = q;
r will now point to the same dynamically allocated object as q. What happens to the object that was created during the initialization of r? Is it still valid? How do you delete it?
I know that writing:
delete q;
will invalidate both q and r. If I did:
delete r;
won't this invalidate both q and r also?
And even if it did wouldn't the original int object with value 100 still be hanging around?
What happens to the object that was created during the initialization of
r?
Nothing.
Is it still valid?
Yes.
How do you
deleteit?
You can't. You just lost the only pointer to it. It will lurk in the background for the rest of the program's lifetime (and even beyond, on some primitive operating systems). This is known as a memory leak.
This is one of many good reasons not to use raw pointers to manage resources. If you used smart pointers, there would be no leak. It's also a good reason to avoid new unless you actually need dynamic allocation.
won't this invalidate both
qandralso?
Yes. Deleting an object invalidates all pointers to it. This is another good reason not to use raw pointers: there is no way to tell that they've been invalidated.
Answers to your questions are:
You cannot delete that object now as you are not referring to it in anyway, thus causing a memory leak.(try using smart pointers)
You cannot delete the object unless you have a pointer referring to it.
Deleting an object invalidates all the pointers pointing to that object.
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