Ast*_*nus 7 c++ stl function-pointers c++14
我尝试使用指向函数的指针(不是指向成员函数的指针)调用std::thread完美的转发构造template< class Function, class... Args > explicit thread( Function&& f, Args&&... args );函数(),如下面的M(N)WE所示:
#include <thread>
#include <string>
static void foo(std::string query, int & x)
{
while(true);
}
int main() {
int i = 1;
auto thd = std::thread(&foo, std::string("bar"), i);
thd.join();
}
Run Code Online (Sandbox Code Playgroud)
现场演示:https://godbolt.org/g/Cwi6wd
为什么代码不能在GCC,Clang和MSVC上编译,抱怨缺少invoke(或类似名称)的重载?函数参数是指向函数的指针,因此它应该是a Callable,对吧?
请注意:我知道使用lambda可以解决问题; 我想了解问题出现的原因.
std::thread存储传递的参数的副本.正如Massimiliano Janes指出的那样,在呼叫者的背景下进行了临时评估.对于所有意图和目的,最好将其视为const对象.
因为x是非const引用,所以它不能绑定到线程提供给它的参数.
如果你想x参考i,你需要使用std::reference_wrapper.
#include <thread>
#include <string>
#include <functional>
static void foo(std::string , int & )
{
while(true);
}
int main() {
int i = 1;
auto thd = std::thread(foo, std::string("bar"), std::ref(i));
thd.join();
}
Run Code Online (Sandbox Code Playgroud)
该实用程序std::ref将动态创建它.