Reputation: 49
I am very confused of how to delete a pointer that's has been called from async function. What do I have:
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:
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. 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. 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. Thanks
Upvotes: 0
Views: 153
Reputation: 12332
Take and return std::shared_ptr<Obj>
to signal that ownership of the pointer is shared. This will also automatically take care of freeing the Obj when the everybody is done with it (all shared_ptr go out of scope).
Look at std::make_shared for a simple way to create the shared pointer.
Upvotes: 2