简体   繁体   English

c ++ 2指向同一对象的指针

[英]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? 我想知道我是否有2个指向同一对象的指针,然后使用指针1删除它,它是否仍在内存中并且指针2将指向null,或者对象将保留在内存中,并且我需要使用删除指针2来免费吗?

I mean: 我的意思是:

int *p1, *p2;
p1=new int;
p2=p1;
*p1=5;
p2=p1;
delete p1;

int x=*p2;
//Error or x=5?
  • The object will be gone . 该对象将消失
  • Pointer 2 will not be a null pointer, but a dangling pointer, with its previous but now-invalid value; 指针2将不是一个空指针,而是一个悬空指针,其前一个值现在无效。 doing anything with it will be an error. 用它做任何事都会是一个错误。 1 1个
  • That's exactly true for pointer 1, too. 指针1也是如此。 There will be no difference between the two. 两者之间没有区别。

1 - Well, UB, not an "error" per se. 1-好吧,UB,本质上不是“错误”。 But don't do it. 但是不要这样做。

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; 在您的情况下(我假设您忘记执行p2=p1 ,如您的问题所示), int x=*p2; is undefined, since the memory p2 points to was deleted. 由于内存p2指向的已删除,因此未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM