How to combine the use of std::bind with std::shared_ptr

Stephane Rolland picture Stephane Rolland · Nov 7, 2012 · Viewed 11.4k times · Source

I need to do something like this more than often:

AsyncOperation * pAsyncOperation = new AsyncOperation();
auto bindOperation = std::bind(&AsyncOperation::operator(), std::ref(*pAsyncOperation));
std::thread thread(bindOperation );
thread.join();

with AsyncOperation being any custom class implementing operator() (also known as function object).

Is it possible to indicate to the std::bind to use a std::shared_ptr instead of a std::ref ? This would prevent memory leaks, without my needing to keep a reference on pAsyncOperation, and would delete the AsyncOperation automatically at the end of the thread, that is the end of this asynchronous task.

EDIT: I don't always have access to std::thread, the thread library can be boost::thread or even any other platform dependent threads. And by consequence, not access to std::async.

My main issue is to have a notion of ownership in the std::bind.

Answer

PiotrNycz picture PiotrNycz · Nov 7, 2012

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