Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector: contiguous data and copy/move

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;
}
like image 869
Shibli Avatar asked Jun 21 '14 22:06

Shibli


1 Answers

According to the standard § 23.3.6.1 Class template vector overview [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().

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));
like image 146
101010 Avatar answered Oct 30 '22 15:10

101010