我想知道如何delete[]
知道动态分配数组的大小,我发现this问题(还有 this 微软论坛上的问题,但答案是相似的)。结果是 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
一个你知道大小的空间。您可以直接传递它,或将其存储在您控制的某个地方。这并不比通过 malloc 的实现查找更糟糕。
关于c++ - 我可以像 `delete[]` 那样获取动态分配数组的大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67871615/