gpt4 book ai didi

c++ - 删除在 C++ 中使用 malloc 分配的 std::string 数组

转载 作者:太空宇宙 更新时间:2023-11-04 15:17:45 25 4
gpt4 key购买 nike

这是我的问题的跟进:Array of strings with malloc on C++

因为我已经实现了 Tony D 解决方案,所以我已经为 std::string 的数组分配了内存。与 malloc然后创建了 std:string对于每个带有 new 的元素根据:

void* TP = malloc(sizeof (string) * SS);
for (int i = 0; i < SS; i++) {
new (&((string*)TP)[i]) std::string(Token[i]);
}

(Token 是一个 vector<string>SS 一个 int )

I know this is not recommended, I know it is not elegant, I know there are many other solutions for this array creation and filling, but I need to do it this way

我现在遇到的问题是数组删除。当我创建每个 std::string单独但分配给带有 malloc 的数组,在我的析构函数中我写了:

for (int i = 0; i < SS; i++) {
delete (&((string*) TP)[i]);
}
free(TP);

但是在运行时,free(TP)正在指责“双重自由或腐败”。

通过评论 free(TP)我解决了运行时的问题(隐藏了真正的问题),但我需要确保释放所有内存,因为这可能会导致类内的内存泄漏。

那么,删除 TP 的每个元素是否足以释放所有内存?据我了解 malloc已独立分配内存,它需要独立于 std::string 释放要素;但是,为什么我会收到此错误?

最佳答案

你正在做一个 placement-new 来在 malloc 分配的 block 上运行 std::string 的构造函数,但是你正在使用 delete 将运行析构函数并尝试释放内存(你不想在这里做第二个,因为你正在使用 free() 释放内存)。

您想像这样手动运行析构函数...

for (int i = 0; i < SS; i++) {
(&((string*) TP)[i])->~string();
}
free(TP);

关于c++ - 删除在 C++ 中使用 malloc 分配的 std::string 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28057999/

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