简体   繁体   中英

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;
}

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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