问题描述
我知道C ++中没有办法获得动态创建的数组的大小,例如:
I know that there is no way in C++ to obtain the size of a dynamically created array, such as:
int* a;
a = new int[n];
我想知道的是:为什么?人们只是在C ++的规范中忘记了这一点,还是有技术上的原因呢?
What I would like to know is: Why? Did people just forget this in the specification of C++, or is there a technical reason for this?
不是信息存储在哪里?毕竟,命令
Isn't the information stored somewhere? After all, the command
delete[] a;
似乎知道它有多少内存要释放,所以在我看来, delete []
有某种方式知道 a
的大小。
seems to know how much memory it has to release, so it seems to me that delete[]
has some way of knowing the size of a
.
推荐答案
你会经常发现内存管理器只会分配一定的倍数,例如64字节的空间。
You will often find that memory managers will only allocate space in a certain multiple, 64 bytes for example.
请求新的int [4],即16个字节,但内存管理器将为您的请求分配64个字节。要释放这个内存,它不需要知道你需要多少内存,只是它已经分配给你一个64字节的块。
So, you may ask for new int[4], i.e. 16 bytes, but the memory manager will allocate 64 bytes for your request. To free this memory it doesn't need to know how much memory you asked for, only that it has allocated you one block of 64 bytes.
下一个问题可能是,它能不能存储请求的大小?这是一个额外的开销,并不是每个人都准备支付。 Arduino Uno例如只有2k的RAM,在这种情况下,每个分配的4个字节突然变得重要。
The next question may be, can it not store the requested size? This is an added overhead which not everybody is prepared to pay for. An Arduino Uno for example only has 2k of RAM, and in that context 4 bytes for each allocation suddenly becomes significant.
如果你需要那个功能,那么你有std ::矢量(或等效的),或者你有更高级的语言。 C / C ++旨在使您能够使用尽可能少的开销,这是一个例子。
If you need that functionality then you have std::vector (or equivalent), or you have higher-level languages. C/C++ was designed to enable you to work with as little overhead as you choose to make use of, this being one example.
这篇关于C ++不告诉你动态数组的大小。但为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!