C++ global vector assignment

Viewed 59

While I'm reading some codes for algorithms, i wonder how the code below works in C++.

#include <vector>
std::vector<int> globalVector;
void initVector() {
    globalVector = std::vector<int>(5,0);
}

I learned that vector assignment '=' operation is a copy operation, but how the uninitialized global vector is copied? Is it a just series of resizing of the vector and copying the contents of counterpart? Thank you!

1 Answers

globalVector is initialized.

std::vector<int> globalVector; This statement define a global variable, it calls the default constructor of std::vector. Now globalVector is an empty vector.

globalVector = std::vector<int>(5,0); This will call move assignment operator since the std::vector<int>(5, 0) is a temporary object.

So it's not a copy, but a movement. What is happening under the hood depends on the compiler implementation. It can swap the internal pointer or copy the temporary internal pointer to the global variable and set the temporary internal pointer to nullptr. (Maybe some ways else)

Related