I was reading std template library book and was confused with below details listed in STL Containers chapter. Apparently, it specifies the STD::VECTOR Operations and the effect
Operation Effect
vector<Elem> c(c2) | Copy constructor; creates a new vector as a copy of c2 (all elements are copied)
vector<Elem> c = c2 | Copy constructor; creates a new vector as a copy of c2 (all elements are copied)
vector<Elem> c(rv) | Move constructor; creates a new vector, taking the contents of the rvalue rv (since C++11)
vector<Elem> c = rv | Move constructor; creates a new vector, taking the contents of the rvalue rv (since C++11)
Apparently, there is no difference in the syntax for both move and copy constructors, when exactly are they called?
Let say you have a function f
that returns a vector by value:
std::vector<int> f();
The value returned by the function is an rvalue.
And then lets say you want to call this function to initialize a vector of yours:
std::vector<int> v = f();
Now the compiler knows the vector returned by f
will not be used any more, it's a temporary object, therefore it doesn't make sense to copy this temporary object since it will just be destructed at once anyway. So the compiler decides to call the move-constructor instead.
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