简体   繁体   English

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

[英]Move item to a list without copying

Given 特定

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

How should I move bar to the end of foo without copying data? 如何在不复制数据的情况下将bar移动到foo的末尾?

Is this ok? 这个可以吗?

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

Is this ok? 这个可以吗?

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

Yes, because: 是的,因为:

  1. std::move(bar) casts bar to an rvalue reference . std::move(bar)bar转换为右值引用

  2. std::list::emplace_back takes any number of forwarding references and uses them to construct an element at the end. std::list::emplace_back接受任意数量的转发引用,并使用它们在最后构造一个元素。

  3. std::vector::vector has an overload (6) that takes an rvalue reference , which moves the contents of the rhs vector without performing any copy. std::vector::vector有一个重载(6) ,它接受一个右值引用 ,它移动rhs向量的内容而不执行任何副本。

Yes, the code in the Q is certainly OK. 是的,Q中的代码当然可以。 Even using push_back would be OK: 即使使用push_back也没关系:

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

How should I move bar to the end of foo without copying data? 如何在不复制数据的情况下将bar移动到foo的末尾?

Using the move constructor of std::vector : 使用std::vector的move构造函数:

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

Is this ok? 这个可以吗?

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

That is OK as well. 那也没关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM