如果STL容器对象的值不是可复制构造的,例如std :: thread,则如何将STL容器对象追加/复制到另一个对象

iam*_*ind 5 c++ stl compiler-errors rvalue c++11

我想移动的std::map容器对象到另一个.最简单的形式:

#include<map>
#include<thread>
#include<vector>
using namespace std;

int main ()
{
  map<void*, vector<thread>> m1, m2; 
  // m1 is updated 

  m1.insert(m2.begin(), m2.end());  // <--- problem here
  m2.clear();  // not required anymore
}
Run Code Online (Sandbox Code Playgroud)

但它会给出一页错误:

error: use of deleted function ‘std::thread::thread(const std::thread&)’
Run Code Online (Sandbox Code Playgroud)

怎么做到这一点?

0x4*_*2D2 11

std::thread 不是可复制构造的,你必须使用允许移动的迭代器:

m1.insert(std::make_move_iterator(m2.begin()),
          std::make_move_iterator(m2.end());
Run Code Online (Sandbox Code Playgroud)

std::make_move_iterator返回一个专门的迭代器类,std::move_iterator其访问成员(operator*()和operator->())返回对rvalues的引用,而不像返回lvalues的内置迭代器.map::insert()将其操作委托给map::emplace()将参数转发到元素类型的位置.

正在调用线程的复制构造函数,因为从内置迭代器返回的对象被转发为左值并因此被复制.


Ric*_*ges 5

只是为了完整性,有一个鲜为人知的版本std::move在<algorithm>一个遵循类似的模式std::copy.

所以你可以这样写:

move(begin(m2), end(m2), inserter(m1, begin(m1)));
m2.clear();
Run Code Online (Sandbox Code Playgroud)

这里参考