[英]c++: how to delete a pointer created/modified in an async function?
I am very confused of how to delete a pointer that's has been called from async function. What do I have:我很困惑如何删除从异步 function 调用的指针。我有什么:
Obj* doStuff(int size){
Obj *myObject = new Obj(size);//where do I delete this?
myObject.doSomeOtherStuffWhichChangesMyObject();
return myObject;
}
int main (){
for (int i = 0; i < CORES; i++)
{
std::shared_future<Obj*> f = std::async(std::launch::async, doStuff,5);
futures.push_back(f);
}
return;
}
I am not very sure of the proper design to do it.我不太确定这样做的正确设计。 My first thought was to create the new Obj* before calling the function:
我的第一个想法是在调用 function 之前创建新的 Obj*:
Obj* doStuff(Obj *myObject){
myObject.doSomeOtherStuffWhichChangesMyObject();
return myObject;
}
int main (){
for (int i = 0; i < CORES; i++)
{
Obj *myObject = new Obj(5);//where do I delete this?
std::shared_future<Obj*> f = std::async(std::launch::async, doStuff, myObject);
futures.push_back(f);
}
return;
}
Then I realized that I cannot delete the new Obj because it's been used by other async processes.然后我意识到我无法删除新的 Obj,因为它已被其他异步进程使用。 So my last solution is to create a double pointer** before the for loop to store the address of every new Obj created in the for loop and delete everything after the loop .
所以我最后的解决方案是在for循环之前创建一个双指针 ** 来存储在 for 循环中创建的每个新 Obj 的地址,并删除循环之后的所有内容。 However, I am not sure if this is the proper design to do it.
但是,我不确定这是否是正确的设计。 Can you please suggest a way that would solve this problem?
你能建议一种解决这个问题的方法吗? I think I mostly need a design/examples of how to delete a pointer created (i) inside a function (ii) inside a for loop.
我想我主要需要一个设计/示例,说明如何删除在 for 循环内的 function (ii) 内创建的指针 (i)。 Thanks
谢谢
Take and return std::shared_ptr<Obj>
to signal that ownership of the pointer is shared.获取并返回
std::shared_ptr<Obj>
以表示指针的所有权是共享的。 This will also automatically take care of freeing the Obj when the everybody is done with it (all shared_ptr go out of scope).当每个人都完成它时,这也将自动负责释放 Obj(所有 shared_ptr go 超出范围)。
Look at std::make_shared for a simple way to create the shared pointer.查看 std::make_shared 以了解创建共享指针的简单方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.