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();
}

 

posted @ 2014-08-19 15:30  Reddington  阅读(432)  评论(0编辑  收藏  举报