How to combine the use of std::bind with std::shared_ptr
This works:
struct AsyncOperation {
void operator()()
{
std::cout << "AsyncOperation" << '\n';
}
};
int main() {
std::shared_ptr<AsyncOperation> pAsyncOperation = std::make_shared<AsyncOperation>();
auto bindOperation = std::bind(&AsyncOperation::operator(), pAsyncOperation);
std::thread thread(bindOperation );
thread.join();
}
See: http://liveworkspace.org/code/4bc81bb6c31ba7b2bdeb79ea0e02bb89
Do you need AsyncOperation
to be allocated dynamically? If not, I would do that:
auto f = std::async([]{ AsyncOperation()(); });
f.wait();
otherwise:
std::unique_ptr<AsyncOperation> op(new AsyncOperation);
auto f = std::async([&]{ (*op)(); });
f.wait();
You can of course use std::thread
, but it can provide more problems (i.e. exception handling in other thread). std::bind
has also its own problems and you will probably better end up with a lambda.
If you really need to pass an ownership to other thread you can also do that:
std::unique_ptr<AsyncOperation> op(new AsyncOperation);
auto f = std::async([&](std::unique_ptr<AsyncOperation> op){ (*op)(); }, std::move(op));
f.wait();
as lambdas do not support move type captures yet.
I hope that helps.