Copying std::vector: prefer assignment or std::copy?

Generally I would strongly prefer v2 = v1:

  1. It is shorter and makes the intent more clear
  2. std::copy won’t work if v2 doesn’t have the same length as v1 (it won’t resize it, so it will retain some of the old elements best case (v2.size() > v1.size() and overwrite some random data used elsewhere in the program worst case
  3. If v1 is about to expire (and you use C++11) you can easily modify it to move the contents
  4. Performancewise assignment is unlikely to be slower then std::copy, since the implementers would probably use std::copy internally, if it gave a performance benefit.

In conclusion, std::copy is less expressive, might do the wrong thing and isn’t even faster. So there isn’t really any reason to use it here.

Leave a Comment