gpt4 book ai didi

c++ - 为 POD 适当分配内存

转载 作者:行者123 更新时间:2023-11-28 06:47:48 25 4
gpt4 key购买 nike

我的回答here收到关于我代码中内存分配的评论。我用过 new[]delete[] ,因为我以前读过,你永远不应该 malloc()/free()在 C++ 中(即 here )。有问题的代码本质上是:

ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
GetAdaptersAddresses(0, 0, NULL, NULL, &outBufLen);
PIP_ADAPTER_ADDRESSES pCurrAddresses = (IP_ADAPTER_ADDRESSES *)new uint8_t[outBufLen];
//...
delete[] pCurrAddresses;

我要分配的内存字节大小来自函数 GetAdaptersAddresses() .我的问题是:这段代码有什么问题吗?如果是,现代 C++ 中分配内存的正确方法是什么?

  • malloc()/free()应该是毫无疑问的——它是 C++ 代码,我没有看到使用 malloc() 有任何改进。而不是 new[]这里。对吧?

  • std::vector<>对我来说似乎不合适 - 我可以写 std::vector<uint8_t> bytes(outBufLen, 0); PIP_ADAPTER_ADDRESSES pCurrAddresses = (IP_ADAPTER_ADDRESSES *)bytes.data();但我会有一个坏感觉,因为std::vector<>::data()是常量)。

  • 使用 std::unique_ptr<uint8_t[]>看起来也很奇怪 - 因为无论如何我都必须将它转换为原始指针。

还有其他选择吗?

最佳答案

在大多数情况下,您对 std::vector 的第二个建议在 C++ 中是正确的。 data() 不是 const(好吧,它用于 const vector ,但在您的情况下不是)。 C++ 标准确保 data() 返回指向 POD 的连续内存存储的指针。

关于c++ - 为 POD 适当分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24649164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com