I have two questions for the following code: 1) Will the elements of faces be contiguous?
2) Does std::vector copy or move Face f when inserting it?
#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;
}
According to the standard § 23.3.6.1 Class template vector overview [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().
As far as it concerns your second question in prior C++11 compilers push_back would copy the object you push back.
After C++11 it depends because push_back has two overloads, one that takes an lvalue reference and another one that takes an rvalue reference.
In your case It will be copied because you are passing the object as an lvalue. To ensure movement of the object you could use std::move().
faces.push_back(std::move(f));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With