noisy cat
noisy cat

Reputation: 3065

c++ 2 pointers to same object

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

Answers (2)

Luchian Grigore
Luchian Grigore

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

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

  • The object will be gone.
  • Pointer 2 will not be a null pointer, but a dangling pointer, with its previous but now-invalid value; doing anything with it will be an error.1
  • That's exactly true for pointer 1, too. There will be no difference between the two.

1 - Well, UB, not an "error" per se. But don't do it.

Upvotes: 8

Related Questions