[英]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: 是的,因为:
std::move(bar)
casts bar
to an rvalue reference . std::move(bar)
将bar
转换为右值引用 。
std::list::emplace_back
takes any number of forwarding references and uses them to construct an element at the end. std::list::emplace_back
接受任意数量的转发引用,并使用它们在最后构造一个元素。
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 offoo
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.