为什么是std :: packed_task< void()>无效? [英] Why is std::packaged_task<void()> not valid?
问题描述
使用MSVC2012,
以下代码将按预期进行编译和运行
std :: packaged_task< int()> task([]() - > int {std :: cout<<hello world<< std :: endl; return 0;});
std :: thread t(std :: move(task));
t.join();以下代码将无法编译和运行
$ b $
b
std :: packaged_task< void()> task([](){std :: cout<<hello world<< std :: endl;});
std :: thread t(std :: move(task));
t.join();
为什么会这样?
:
作为一种解决方法,可以使用std :: promise在返回void的函数上获取std :: future。
std :: promise< void>诺言;
auto future = promise.get_future();
std :: thread thread([](std :: promise< void>& p){std :: cout<<hello world<< std :: endl; p.set_value );},std :: move(promise));
future.wait();
请注意,vs2012库中有一个带std :: thread的错误,承诺作为l值引用并移动promise,如果你通过值或r值引用传递promise,它将不会编译。这是因为实现使用的std :: bind()的行为不符合预期。
解决方案 MSVC2012。在MSVC2012附带的线程库实现中有相当多的错误。我发布了一个部分列表在我的博客文章比较它我的商业Just :: Thread图书馆: http://www.justsoftwaresolutions.co.uk/news/just-thread-v1.8.0-released.html
Using MSVC2012,
The following code will compile and run as expected
std::packaged_task< int() > task( []()->int{ std::cout << "hello world" << std::endl; return 0; } );
std::thread t( std::move(task) );
t.join();
while the following code will fail to compile and run
std::packaged_task< void() > task( [](){ std::cout << "hello world" << std::endl; } );
std::thread t( std::move(task) );
t.join();
Why is this so?
Edit:
As a workaround, it is possible to use std::promise to get a std::future on a function that returns void
std::promise<void> promise;
auto future = promise.get_future();
std::thread thread( [](std::promise<void> &p){ std::cout << "hello world" << std::endl; p.set_value(); }, std::move(promise) );
future.wait();
Note that there is a bug in the vs2012 library with std::thread that forces you to pass the promise in as a l-value reference and move the promise in, it would not compile if you pass the promise by value or by r-value reference. This is supposedly because the implementation uses std::bind() which does not behave as expected.
解决方案 This is a bug in MSVC2012. There are quite a few bugs in the thread library implementation that ships with MSVC2012. I posted a partial list in my blog post comparing it to my commercial Just::Thread library: http://www.justsoftwaresolutions.co.uk/news/just-thread-v1.8.0-released.html
这篇关于为什么是std :: packed_task< void()>无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!