c++ swap global and local vector?

I want to swap a global vector and a local vector, and my question is the local vector is on he stack.The swap operator will exchange two vector by pointer, so after swap, the global vector will point to the local vector, which is on stack.

When leave the scope, the local vector will be released, I know the contents of the vector is swaped, but y is on stack, and why x is still valid after leave func scope, y will realeased after that. How is this done?

#include <iostream>
#include <vector>

using namespace std;

vector<int> x = {2, 3, 4};

void func() {
    vector<int> y = {1, 2, 3};
    cout << "y before: " << &y << endl;
    x.swap(y);
    cout << "y after: " << &y << endl;
}

int main()
{
    cout << "x before: " << &x << endl;
    func();
    cout << "x after: " << &x << endl;
    return 0;
}


Read more here: https://stackoverflow.com/questions/66270600/c-swap-global-and-local-vector

Content Attribution

This content was originally published by dahohu527 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: