std::vector 个 std::thread 个后代
std::vector of std::thread descendants
我正在尝试创建一个具有 属性 销毁时自动连接的线程向量。 Stroustrup 建议 guarded_thread:
struct guarded_thread : std::thread {
using std::thread::thread;
~guarded_thread() { if (joinable()) join(); }
};
这个guarded_thread很有魅力:
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() 使编译器发出一条很长的错误消息,抱怨 "type" not found in 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
大致都抱怨同一个错误。
似乎 guarded_thread
缺少默认的移动构造函数,应该删除复制构造函数。
Here 是一个工作示例。
guarded_thread(const guarded_thread&) = delete ;
guarded_thread(guarded_thread&&) = default ;
注意:您的代码正在调用已删除的函数,即 std::thread
复制构造函数,也没有提供移动构造函数。
我正在尝试创建一个具有 属性 销毁时自动连接的线程向量。 Stroustrup 建议 guarded_thread:
struct guarded_thread : std::thread {
using std::thread::thread;
~guarded_thread() { if (joinable()) join(); }
};
这个guarded_thread很有魅力:
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() 使编译器发出一条很长的错误消息,抱怨 "type" not found in 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
大致都抱怨同一个错误。
似乎 guarded_thread
缺少默认的移动构造函数,应该删除复制构造函数。
Here 是一个工作示例。
guarded_thread(const guarded_thread&) = delete ;
guarded_thread(guarded_thread&&) = default ;
注意:您的代码正在调用已删除的函数,即 std::thread
复制构造函数,也没有提供移动构造函数。