dimanche 15 novembre 2020

Vector building optimization using std::move

I'm building some std::vector<Obj> where Obj are large objects which can be move constructed and assigned (think eg of Obj being large vectors). The code is typically a loop such as

std::vector<Obj> v;
while (...) {
    Obj foo;
    // ... some complicated stuff modifying foo
    v.push_back(foo);
}

As you can see, foo is not needed after being pushed in the vector.

My questions are

  • Does is make sense to write

      v.push_back(std::move(foo));
    

    to indicate to the compiler that it can take the contents of foo.

  • if it does, is it actually needed ? Indeed the compiler might notice that foo is destructed right after being pushed so that it can be moved ? Does actual compiler use those kinds of optimisation ?

Aucun commentaire:

Enregistrer un commentaire