zoukankan      html  css  js  c++  java
  • C++ thread operator= 右值引用 vector foreach

    这是 thread 的construct定义:

    default (1)
    thread() noexcept;
    
    initialization (2)
    template <class Fn, class... Args>
    explicit thread (Fn&& fn, Args&&... args);
    
    copy [deleted] (3)
    thread (const thread&) = delete;
    
    move (4)
    thread (thread&& x) noexcept;

    可以看到thread是无法copy的,他的=操作符的定义:

    move (1)
    thread& operator= (thread&& rhs) noexcept;
    
    copy [deleted] (2)
    thread& operator= (const thread&) = delete;

    只允许右值引用(http://stackoverflow.com/questions/3106110/what-are-move-semantics),所以如果要vector<thread> 必须要这么写:

    std::vector<std::thread> threads;
      for (int i=1; i<=10; ++i)
        threads.push_back(std::thread(increase_global,1000));   
    //分开写: thread t()
    // thread.push_back(t) 就无法编译通过,因为要用到operator= ,而 thread只允许move semnantics,就是只允许右值引用

    类似的 对于c++11 里的for each ,可以解释为 http://en.cppreference.com/w/cpp/language/range-for
    {
    auto && __range = range_expression ; 
    for (auto __begin = begin_expr,
    __end = end_expr; 
    __begin != __end; ++__begin) { 
    range_declaration = *__begin; // 这里需要operator=
    loop_statement 

    所以range for 也不可用于thread

    但是可以这么用:
    for( auto& x : threads){
      x.join();
    }
  • 相关阅读:
    pytroch tensor初始化权重、改变tensor某行列为指定值
    蜜蜂寻路
    童年生活二三事
    母牛的故事
    星际密码
    斐波那契凤尾
    客似云来
    养兔子
    NowCoder数列
    采花生
  • 原文地址:https://www.cnblogs.com/Sorean/p/3922221.html
Copyright © 2011-2022 走看看