简体   繁体   中英

Is it Safe to Assign vector With operation= vector() in C++

Is it safe to assign vector later after initialization.

Let say i have a global vector variable. But i don't want to initialize the value at the beginning.

#include <iostream>
#include <vector>

using namespace std;

vector<int> globalVector;
int myNumber=123;

void setVector()
{
    // Is it safe to set the vector as shown below ?
    globalVector = vector<int>{1,2,3,4};
}
int main(int, char**) {

    setVector();
    for (int x=0; x<globalVector.size();x++)
    {
        cout << "Val = " << globalVector[x] << endl;
    }
    std::cout << "Hello, world! : " << myNumber << endl;
    return 0;
}

on VSCode i can see some information said:

std::vector<int> &std::vector<int>::operator=(std::vector<int> &&__x)

+2 overloads

%Vector move assignment operator.

Parameters: __x – A %vector of identical element and allocator types. The contents of __x are moved into this %vector (without copying, if the allocators permit it). Afterwards __x is a valid, but unspecified %vector. Whether the allocator is moved depends on the allocator traits.

The description said "move without copying". will the globalVector corrupt when the program exit from function setVector?

Yes that is safe, although

  1. The notation globalVector = {1,2,3,4}; is clearer.

  2. It's not thread-safe .

  3. Use globalVector.at(x) rather than globalVector[x] unless performance really matters, as the behaviour of the latter can be undefined for some values of x . In this particular case, a range-for loop would be better still: for (auto&& i: globalVector) .

The description said "move without copying". will the globalVector corrupt when the program exit from function setVector?

It means that operator= moved content of new vector without copy operation. The vector used for initialization is invalid after that operation. However it doesn't impact you since it is the object used only for initialization so is destroyed just after that.

Yes, it is totally safe, but I recommend you not to use global vector

instead write

int main() {

std::vector globalVector = vector{1,2,3,4};

for (int i=0; i<globalVector.size();i++) {

    cout << "Val = " << globalVector.at(i) << '\n';

}

std::cout << "Hello, world! : " << myNumber << '\n';

return 0;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM