《C++并发编程》21页为什么说这里data传递的是副本,根据模板推导规则,传递不应该是...
source link: https://www.zhihu.com/question/449957754/answer/1786388445
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
《C++并发编程》21页为什么说这里data传递的是副本,根据模板推导规则,传递不应该是左值引用吗?
事实上这段代码无法通过编译。因为你为一个函数调用而起一个线程,而这个函数入参传引用,那么无法保证入参的生命周期,很可能造成悬挂引用导致程序挂掉。
为了避免这种问题,标准库会进行静态检查,通过编译报错让你无法传引用。
static_assert(__is_invocable<typename decay<_Callable>::type,
typename decay<_Args>::type...>::value,
"std::thread arguments must be invocable after conversion to rvalues"
);
The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g., with std::ref or std::cref).
Any return value from the function is ignored. If the function throws an exception, std::terminate is called. In order to pass return values or exceptions back to the calling thread, std::promise or std::async may be used.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK