简体   繁体   English

vector的emplace_back

[英]vector's emplace_back

Can you please explain how "perfect forwarding" works? 你能解释一下“完美转发”的工作原理吗?

I read that vector's emplace_back doesn't need to copy nor move objects, because its argument is implemented as variadic template. 我读到vector的emplace_back不需要复制或移动对象,因为它的参数是作为可变参数模板实现的。

std::vector<T>::emplace_back(_Args&&... __args)

Can you describe it in more detail? 你能更详细地描述一下吗? Why won't it copy nor move? 为什么不复制或移动?

emplace_back directly constructs the element at the correct position in the vector. emplace_back直接在向量中的正确位置构造元素。 Think of it as if 把它想象成一样

vector<T> v;
v.emplace_back(a,b,c);

is transformed into (idx being the new index) 被转换成(idx是新索引)

new (v.data()+idx) T(a,b,c);

(The reality is a bit more complex involving forwarding the arguments as std::forward<_Args>()... but that might be more confusing to get the key of emplace operations) (现实有点复杂,涉及将参数转发为std::forward<_Args>()...但这可能会更加令人困惑,无法获得安卓操作的密钥)

There are actually two things happening in emplace_back: emplace_back实际上发生了两件事:

  1. You don't pass an object of type T but arguments to a constructor of T. This way, object construction is delayed: the vector is extended to accomodate for the memory needed by the new object, and the constructor is called to initialized the object in the vector. 你没有传递T类型的对象,而是传递T的构造函数。这样,​​对象构造被延迟:向量被扩展以适应新对象所需的内存,并且调用构造函数来初始化对象在向量中。 Variadic template don't have anything to do with copies, they only allow forwarding a variable number of arguments to the constructor. Variadic模板与副本没有任何关系,它们只允许将可变数量的参数转发给构造函数。
  2. Arguments to the constructors themselves are not copied because they are passed as rvalues references and std::move is used to forward them to the constructor. 构造函数本身的参数不会被复制,因为它们作为rvalues引用传递,std :: move用于将它们转发给构造函数。 Basically, move semantics avoid deep copies of objects. 基本上,移动语义避免了对象的深层复制。

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

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