简体   繁体   中英

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM