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

标签 c++ portability dynamic-arrays

我想知道如何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/

相关文章:

c++ - Makefile - 创建一个静态库

c++ - 如何在 QLineEdit 中使用 std::string?

c++ - 如何在 C++ 中初始化自定义结构的动态数组

javascript - Array.every 返回 false 而不是 true

c++ - 为什么最后两个程序中的 sum 值不同?

c++ - 理解 C++ 中的多维字符串数组

python - 在不使用第三个变量的情况下交换 2 个变量的 2 个值; Python

java - 将数据导入到不同平台上的Java程序中?

c - 通过 config.h 可移植地访问 sysconfdir

arrays - 将项目添加到数组的最快方法