Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a C++ compiler decide when to call a move constructor for std::vector or any object

Tags:

c++

c++11

stl

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?

like image 427
LearningCpp Avatar asked Dec 10 '22 15:12

LearningCpp


1 Answers

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.

like image 167
Some programmer dude Avatar answered May 29 '23 03:05

Some programmer dude