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

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

问题描述

好吧,我想我们大家都同意,有以下code会发生什么是不确定的,取决于什么传递,

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;
}

该指针可以是各种不同的东西,所以执行无条件删除[] 它是不确定的。然而,让我们假设,我们的确是传递一个数组指针,

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;
}

我的问题是,在这种情况下指针的的数组,是谁,知道吗?我的意思是,从语言/编译器的角度来看,它不知道是否不改编是一个数组指针与一个指向单个int。哎呀,它甚至不知道是否改编动态创建。然而,相反如果我做以下,

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(2);
     deleteForMe(num);
     return 0;
}

该操作系统是足够聪明,只删除一个int和通过删除记忆的其余部分超出该点(对比度上某种类型的'杀小号preE'的不去与的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).

所以,他们的工作是要记住这些事情?是否OS继续在后台某种类型的记录? (我的意思是,我意识到,我最后说,会发生什么是不确定的,但事实是,杀小号preE'的情况不会发生,所以因此现实世界的有人<启动这个帖子/ em>的是要记住。)

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.)

推荐答案

编译器不知道它是一个数组,它的信任程序员。删除指向一个 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 ++超级FAQ

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.

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

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