【发布时间】:2015-03-07 16:38:04
【问题描述】:
我正在尝试创建一个具有销毁时自动连接属性的线程向量。 Stroustrup 建议使用 guarded_thread:
struct guarded_thread : std::thread {
using std::thread::thread;
~guarded_thread() { if (joinable()) join(); }
};
这个受保护的线程就像魅力一样工作:
void f() { std::cerr << "f();" << std::endl; }
int main() { guarded_thread gt(f); }
但只要我不想将其中的几个存储在向量中:
void f() { std::cerr << "f();" << std::endl; }
int main() { std::vector<guarded_thread> v; v.emplace_back(f); }
实际上 emplace_back() 或 push_back() 使编译器发出一条很长的错误消息,抱怨在 std::result_of 中找不到“类型”,但我不明白为什么 std::result_of 会用 guarded_thread 实例化() 作为模板参数。 Thread 在我的 STL 实现上有一个模板构造函数:
template<typename _Callable, typename... _Args>
explicit
thread(_Callable&& __f, _Args&&... __args)
{
#ifdef GTHR_ACTIVE_PROXY
__asm ("" : : "r" (&pthread_create));
#endif
_M_start_thread(_M_make_routine(std::__bind_simple(
std::forward<_Callable>(__f),
std::forward<_Args>(__args)...)));
}
问题是:不知何故 _Callable 被替换为 guarded_thread 但我不明白为什么。也许试图调用复制构造函数?怎么解决?
我尝试了两种不同的编译器:
- g++ (Debian 4.9.1-19) 4.9.1
- Debian clang 版本 3.5.0-9
两者都抱怨同样的错误。
【问题讨论】:
标签: c++ multithreading c++11 vector stl