【问题标题】:std::vector of std::thread descendantsstd::thread 后代的 std::vector
【发布时间】: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


    【解决方案1】:

    似乎guarded_thread 缺少默认的移动构造函数,应该删除复制构造函数。

    Here 是一个工作示例。

    guarded_thread(const guarded_thread&) = delete ;
    guarded_thread(guarded_thread&&) = default ;
    

    注意:您的代码调用了一个已删除的函数,即 std::thread 复制构造函数,并且也没有提供移动构造函数。

    【讨论】:

    • 复制构造函数已在基(线程)中删除。请求默认移动构造函数即可解决问题,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多