【发布时间】:2017-03-22 20:26:17
【问题描述】:
需要让这个 Functor 与我的线程一样长,所以我为它创建了一个 shared_ptr 并尝试将它传递给 std::thread。我在这里复制了代码和错误列表。
struct Functor
{
std::string greeting;
explicit Functor(std::string _greeting="Hello!"): greeting { _greeting } {}
void operator()()
{
std::cout << greeting << "\n";
}
};
auto main() ->int
{
std::shared_ptr<Functor> fp = std::make_shared<Functor> ();
std::thread t(&fp);
t.join();
return 0;
}
错误列表:
Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)' std_threads C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr\xthread 240
Error C2672 'std::invoke': no matching overloaded function found std_threads C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr\xthread 240
我是 C++11 和并发的新手。请帮助我理解以下内容
1>当按值传递时,std::thread 是否总是调用对象内部的 operator() ?如果是,为什么会这样定义。
2>如何确保分配给线程的资源与线程一样长?
3>这里写的Functor是函数对象吗?
4>我在这段代码中做了什么?!
【问题讨论】:
-
不应该是
std::thread t(*fp)吗?
标签: c++ multithreading c++11 shared-ptr functor