将项目移动到列表而不复制

Move item to a list without copying

给定

std::list<std::vector<float>> foo;
std::vector<float> bar;

如何在不复制数据的情况下将bar移动到foo的末尾?

这样可以吗?

foo.emplace_back(std::move(bar));

是的,Q中的代码当然可以。即使使用 push_back 也可以:

foo.push_back(std::move(bar));

How should I move bar to the end of foo without copying data?

使用std::vector的移动构造函数:

foo.push_back(std::move(bar));

Is this ok?

foo.emplace_back(std::move(bar));

也可以。

Is this ok?

foo.emplace_back(std::move(bar));

是的,因为:

  1. std::move(bar)bar 转换为 右值引用

  2. std::list::emplace_back takes any number of forwarding references 并在末尾使用它们构造一个元素。

  3. std::vector::vector 有一个重载 (6) 需要一个 rvalue 引用 ,它移动rhs 向量的内容而不执行任何复制。