删除从另一个指针分配的指针,我应该再次删除另一个指针吗? [英] delete pointer that is assigned from another pointer, should i delete the other one again?

查看:125
本文介绍了删除从另一个指针分配的指针,我应该再次删除另一个指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是我的例子来解释这个问题

so, here is my example to explain this question

void * p1;
int * p2, * p3;

p2 = new int;
p1 = p2;
p3 = (int *) p1;

要释放内存,以下3行是否彼此相等?

to free the memory, are the following 3 lines equivalent to each other?

delete p2;
delete p3;
delete (int *) p1;

我使用这种方法的原因是,我想在函数之间传递一个指针,而又不知道其类型,例如,我定义了一个void指针,并通过调用其他函数来更改其值,如下所示:

the reason i am using such is that i want to pass a pointer between functions without knowing its type, for instance i define a void pointer and changes its value by calling other functions as follow:

void * p1;
func1(p1); //in this function, p2 = new int and  p1 is assigned as p1 = p2;
func2(p1); //in this function, p1 is assigned to another pointer: int * p3 = (int *)p1;

然后,我打电话给func3释放内存

then, i called func3 to release the memory

func3(p1); //delete int * p1

在调用func3之后,我是否还要处理func1中的p2吗?

after calling func3, do i have to deal with p2 in func1 anymore?

谢谢!

推荐答案

是的,所有3个delete都是等效的.重要的是要注意,在发布的示例中,所有3个指针都指向同一件事.这意味着,如果您delete其中一个,则不应delete其他,因为它们所指向的内存已被释放.

Yes, all 3 deletes are equivalent. It's important to note that in the posted example, all 3 pointers point to the same thing. This means if you delete one of them, you should not delete the others as the memory they point to has already been released.

如果您尝试delete已发布的内容,则会引起未定义行为.如果幸运的话,您的程序将崩溃,但是任何事情都可能发生.

If you do try to delete something that has already been released, you'll evoke Undefined Behavior. If you're lucky your program will crash, but anything could happen.

这篇关于删除从另一个指针分配的指针,我应该再次删除另一个指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆