delete[] 如何知道它是一个数组? [英] How does delete[] know it's an array?

查看:26
本文介绍了delete[] 如何知道它是一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我想我们都同意以下代码发生的事情是未定义的,取决于传递的内容,

Alright, I think we all agree that what happens with the following code is undefined, depending on what is passed,

void deleteForMe(int* pointer)
{
     delete[] pointer;
}

指针可以是各种不同的东西,因此对其执行无条件的 delete[] 是未定义的.然而,让我们假设我们确实传递了一个数组指针,

The pointer could be all sorts of different things, and so performing an unconditional delete[] on it is undefined. However, let's assume that we are indeed passing an array pointer,

int main()
{
     int* arr = new int[5];
     deleteForMe(arr);
     return 0;
}

我的问题是,在这种情况下,指针一个数组,谁知道这一点?我的意思是,从语言/编译器的角度来看,它不知道 arr 是数组指针还是指向单个 int 的指针.哎呀,它甚至不知道 arr 是否是动态创建的.但是,如果我改为执行以下操作,

My question is, in this case where the pointer is an array, who is it that knows this? I mean, from the language/compiler's point of view, it has no idea whether or not arr is an array pointer versus a pointer to a single int. Heck, it doesn't even know whether arr was dynamically created. Yet, if I do the following instead,

int main()
{
     int* num = new int(1);
     deleteForMe(num);
     return 0;
}

操作系统足够聪明,可以只删除一个 int 而不会通过删除超出该点的其余内存来进行某种类型的杀戮狂欢"(与 strlen 和一个非\0-终止的字符串——它会一直持续到它到达 0).

The OS is smart enough to only delete one int and not go on some type of 'killing spree' by deleting the rest of the memory beyond that point (contrast that with strlen and a non-\0-terminated string -- it will keep going until it hits 0).

那么记住这些东西是谁的工作?操作系统是否在后台保留某种类型的记录?(我的意思是,我意识到我开始这篇文章时说发生的事情是不确定的,但事实是,杀戮狂欢"场景不会发生,因此在实际世界中某人是记住了.)

So whose job is it to remember these things? Does the OS keep some type of record in the background? (I mean, I realise that I started this post by saying that what happens is undefined, but the fact is, the 'killing spree' scenario doesn't happen, so therefore in the practical world someone is remembering.)

推荐答案

编译器不知道它是一个数组,它信任程序员.使用 delete [] 删除指向单个 int 的指针会导致未定义的行为.您的第二个 main() 示例是不安全的,即使它没有立即崩溃.

The compiler doesn't know it's an array, it's trusting the programmer. Deleting a pointer to a single int with delete [] would result in undefined behavior. Your second main() example is unsafe, even if it doesn't immediately crash.

编译器确实必须跟踪需要以某种方式删除的对象数量.它可以通过过度分配足够的空间来存储数组大小来做到这一点.有关详细信息,请参阅 C++ 超级常见问题解答.

The compiler does have to keep track of how many objects need to be deleted somehow. It may do this by over-allocating enough to store the array size. For more details, see the C++ Super FAQ.

这篇关于delete[] 如何知道它是一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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