Reputation: 3065
I'm wondering if I have 2 pointers pointing same object, and then I delete it using pointer 1, will it still be in memory and pointer 2 will point null, or object will stay in memory and I need to use delete pointer 2 to free it?
I mean:
int *p1, *p2;
p1=new int;
p2=p1;
*p1=5;
p2=p1;
delete p1;
int x=*p2;
//Error or x=5?
Upvotes: 1
Views: 5637
Reputation: 258548
It's generally good not to have two pointers pointing to the same memory. That's because if you delete one, the other will be a dangling pointer.
Anything you do with the memory after deleting it is undefined behavior.
In your case ( I assume you forgot to do p2=p1
, as your question suggests ), int x=*p2;
is undefined, since the memory p2
points to was deleted.
Upvotes: 1
Reputation: 385098
1 - Well, UB, not an "error" per se. But don't do it.
Upvotes: 8