#include <functional>
#include <future>
void z(int&&){}
void f1(int){}
void f2(int, double){}
template<typename Callable>
void g(Callable&& fn)
{
fn(123);
}
template<typename Callable>
std::future<void> async_g(Callable&& fn)
{
return std::async(std::launch::async, std::bind(&g<Callable>, fn));
}
int main()
{
int a = 1; z(std::move(a)); // Does not work without std::move, OK.
std::function<void(int)> bound_f1 = f1;
auto fut = async_g(bound_f1); // (*) Works without std::move, how so?
// Do I have to ensure bound_f1 lives until thread created by async_g() terminates?
fut.get();
std::function<void(int)> bound_f2 = std::bind(f2, std::placeholders::_1, 1.0);
auto fut2 = async_g(bound_f2);
// Do I have to ensure bound_f2 lives until thread created by async_g() terminates?
fut2.get();
// I don't want to worry about bound_f1 lifetime,
// but uncommenting the line below causes compilation error, why?
//async_g(std::function<void(int)>(f1)).get(); // (**)
}
问题1。为什么 (*) 处的调用没有std::move
?
问题2。因为我不明白 (*) 处的代码是如何工作的,所以出现了第二个问题。我是否必须确保每个变量都存在bound_f1
,bound_f2
直到 async_g() 创建的相应线程终止?
问题3。为什么取消注释(**)标记的行会导致编译错误?