我可以像`delete[]` 那样获取动态分配数组的大小吗? [英] Can I get the size of a dynamicly allocated array the way `delete[]` does?

查看:68
本文介绍了我可以像`delete[]` 那样获取动态分配数组的大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 delete[] 如何知道动态分配数组的大小,我发现 this 问题(还有 这个微软论坛上的问题,但答案是相似的).原来答案

I was wondering how delete[] knows the size of a dynamically allocated array, and I found this question (and also this question on a Microsoft forum, but the answer is similar). Turns out the answer is

这通常存储在您分配的内存之前的头"段中.

This is usually stored in a "head" segment just before the memory that you get allocated.

因此确切的细节是特定于实现的.
在该答案下,其中一条评论询问为什么程序员无法获得这条非常有用的信息,这迫使我们传递表示大小的变量.评论得到的答案是

Thus the exact details are implementation specific.
Under that answer one of the comments asks why this quite useful piece of information is not available to the programmers, forcing us to pass around variables denoting the size. The answer the comment got is

强制分配器存储请求的大小(这样你就不需要自己传递数组大小)可能是一个小负担,但它可能会对可以想象的分配器设计产生性能影响

Forcing the allocator to store the requested size (so that you wouldn't need to pass the array size yourself) might be a small encumbrance, but it could have performance impacts on conceivable allocator designs

对我来说,考虑到 delete[] 无论如何都应该可以访问大小,这并不是很有说服力.

To me, that isn't very convincing considering the size should be accessible to delete[] anyhow.

我的问题:(对于程序员)是否有可能以某种方式检索大小?

My question: is it possible (for a programmer) to retrieve the size somehow?

我知道有一种 Microsoft 特殊方式(正如在前面提到的 MS 论坛中指出的那样),但我追求的是标准化.

I am aware that there's a Microsoft special way (as it was noted in the aforementioned MS forum), but I am after something standardized.

您可以使用 Microsoft 特定的函数 _msize() 来从动态分配的数组中获取大小指针,即使它被传递给另一个函数而不是进行分配的那个.

You can use the Microsoft-specific function _msize() to get the size of a dynamically allocated array from the pointer, even when it is passed to another function than the one which did the allocation.

推荐答案

我的结论是:
数组的大小可能存储在内存中,但不一定如此;还有其他方法可以实现所需的行为,每种方法都有自己的权衡,而 ISO 专门为编译器编写者提供了选择的自由,以便他们可以根据需要对其进行优化.
也就是说,目前还没有一种单一的、标准化的方法来获取动态分配数组的大小.

My conclusion is:
The size of the array might be stored in memory, but it is not necessarily the case; there are other ways of achieving the desired behavior, each with its own trade-offs and ISO specifically gives the compiler writers the freedom to choose so that they can optimize it as much as necessary.
That is to say, there is not a single, standardized way of getting the size of a dynamically allocated array as of now.

这篇关于我可以像`delete[]` 那样获取动态分配数组的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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