vendredi 3 mai 2019

How to enable move semantics when adding custom objects to a vector?

Below code passes objects that contain big vectors into a vector. I want this to be performant. Do I need to cast test to rvalue in the call to push_back? Do I need to tell compiler how to move instances of struct Test? Or does this all go automatically?

int main()
{
    struct Test
    {
        std::vector<size_t> vals;
        double sum;
    };
    std::vector<Test> vecOfTest;
    vecOfTest.reserve(100000);

    for (size_t i = 0; i < 100000; i++)
    {
        Test test{};
        test.vals.reserve(i);
        for (size_t j = 0; j < i; j++)
        {
            test.vals.push_back(j);
            test.sum += j;
        }
        vecOfTest.push_back(test);
    }


    return 0;
}

Aucun commentaire:

Enregistrer un commentaire