我有以下代码的两个问题:1)面孔的元素会连续吗?
2)std :: vector复制或移动Face f插入吗?
2)std :: vector复制或移动Face f插入吗?
#include <vector>
int main()
{
struct Face {};
std::vector<Face> faces;
for (int i=0; i<10; ++i)
{
Face f;
faces.push_back (f);
}
return 0;
}
解决方法
根据标准§23.3.6.1类模板向量概述[vector.overview]:
The elements of a
vectorare stored contiguously,meaning that ifvis avector<T,Allocator>whereTis some type other thanbool,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().
faces.push_back(std::move(f));