c – std :: vector:连续数据和复制/移动

前端之家收集整理的这篇文章主要介绍了c – std :: vector:连续数据和复制/移动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码的两个问题:1)面孔的元素会连续吗?
2)std :: vector复制或移动Face f插入吗?
  1. #include <vector>
  2. int main()
  3. {
  4. struct Face {};
  5. std::vector<Face> faces;
  6.  
  7. for (int i=0; i<10; ++i)
  8. {
  9. Face f;
  10.  
  11. faces.push_back (f);
  12. }
  13.  
  14. return 0;
  15. }

解决方法

根据标准§23.3.6.1类模板向量概述[vector.overview]:

The elements of a vector are stored contiguously,meaning that if v is a vector<T,Allocator> where T is some type other than bool,then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

就现在C11编译器而言,第二个问题push_back会复制你推回的对象.

在C 11之后,这取决于因为push_back有两个重载,一个采用一个左值引用,另一个引用一个rvalue引用.

在你的情况下,它将被复制,因为你将对象作为左值传递.为了确保对象的移动,您可以使用std :: move().

  1. faces.push_back(std::move(f));

猜你在找的C&C++相关文章