Create new object with std::async

Is there a way to call a constructor and create a new object with std::async?
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;
Last edited on
auto my_future = std::async([] { return A{}; });
Oh yeah. Or you could just return it.
Topic archived. No new replies allowed.