[英]How to combine the use of std::bind with std::shared_ptr
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) . AsyncOperation
是实现operator()
(也称为函数对象)的任何自定义类。
Is it possible to indicate to the std::bind
to use a std::shared_ptr
instead of a std::ref
?是否可以指示
std::bind
使用std::shared_ptr
而不是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.这将防止内存泄漏,而无需保留对
pAsyncOperation
的引用,并且会在线程结束时自动删除AsyncOperation
,即此异步任务的结束。
EDIT: I don't always have access to std::thread, the thread library can be boost::thread or even any other platform dependent threads.编辑:我并不总是有权访问 std::thread,线程库可以是 boost::thread 甚至任何其他平台相关的线程。 And by consequence, not access to std::async.
因此,无法访问 std::async。
My main issue is to have a notion of ownership in the std::bind.我的主要问题是在 std::bind 中有一个所有权的概念。
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请参阅:http: //liveworkspace.org/code/4bc81bb6c31ba7b2bdeb79ea0e02bb89
Do you need AsyncOperation
to be allocated dynamically?是否需要动态分配
AsyncOperation
? 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 (ie exception handling in other thread).您当然可以使用
std::thread
,但它会带来更多问题(即在其他线程中进行异常处理)。 std::bind
has also its own problems and you will probably better end up with a lambda. std::bind
也有它自己的问题,你可能最好以 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.因为 lambda 还不支持移动类型捕获。
I hope that helps.我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.