我可以像 `delete[]` 那样获取动态分配数组的大小吗?

Can I get the size of a dynamicly allocated array the way `delete[]` does?

我想知道 delete[] 是如何知道动态分配数组的大小的,我发现 this question (and also this question on a Microsoft forum, but the answer is similar). Turns out the answer

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

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

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[] 应该可以访问大小,这不是很有说服力。

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

我知道 Microsoft 有一种特殊的方法(正如前面提到的 MS 论坛中所指出的),但我正在寻求标准化的方法。

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.

如果您使用开源库,那么可以!只需查找来源,弄清楚如何去做。

尽管如此,这仍然是一个坏主意,因为没有任何保证:实现可能随时更改,并且即使在 Unix 和 Linux 之间也不能保证可移植。这个数字也可能太大,因为分配更多可能是有利的,例如对齐。 这也是不必要的:当你 new a space 你就知道大小了。你可以传递它,或者将它存储在你控制的某个地方。这不比通过 malloc 的实现来查找它更糟糕。

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