std::copy
is a more general approach since it can handle containers with differing value types (e.g. copy from std::vector<float>
to std::vector::<double>
). But when the value type is the same for both containers, does it matter whether I use the copy constructor instead of std::copy
?
Don't worry about performance, they should all be super close. Instead:
assign
member.std::copy
.By accurately representing what you're trying to do, you give the compiler the most possible information to optimize its code (for example constructing directly from an existing container it can pre-allocate exactly the right about of memory).
One potentially important difference is when you have a situation where you are able to invoke the move constructor rather than the copy constructor (e.g. when the object you are copy constructing from is an rvalue, such as the return value of a function). If you have such a situation, you definitely want to make sure you take advantage of it by move constructing or move assigning rather than using std::copy.
Basically this is just another reason to follow Mark B's advice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With