Create new object with std::async

Nov 29, 2020 at 6:21pm
Is there a way to call a constructor and create a new object with std::async?
Nov 29, 2020 at 8:49pm
There is. You just create the object you want to create like normal. For example,
string x;
Boom. New object created.

std::async runs on a new thread, so any objects you create inside it will cease to exist when the thread ends and tidies up.

If you want those object to continue to exist, you'll have to create them in some memory that isn't simply tidied up when the thread ends.

Perhaps you could pass a reference to a vector or some such, and have your new object created on the back of that vector. Since the vector would be shared between threads, be sure not to have both threads working on the vector at the same time.

Note that passig things by ref to async is a bit fiddly; https://stackoverflow.com/questions/18359864/passing-arguments-to-stdasync-by-reference-fails
Last edited on Nov 29, 2020 at 8:51pm
Nov 29, 2020 at 9:20pm
auto my_future = std::async([] { return A{}; });
Nov 30, 2020 at 11:45am
Oh yeah. Or you could just return it.
Topic archived. No new replies allowed.