Search code examples
c++vectorstaticstdvectorstatic-variables

static vector doesn't save datas?


I'm a little confused. Indeed, I declared a global vector in a namespace from an header file:

namespace foo {
    ...
    static std::vector<T> vec;
    ...
    void append(T item) {
        vec.push_back(item);
    }
    T get(int index) {
        return vec[index];
    }
}

When I want to recover one of the vector elements at runtime:

foo::append(/* item */);
T ItemFromVec = foo::get(0);

I have this dialog box:

enter image description here

Apparently, the vector would be empty. I guess the problem is that it's static, but I get errors from the linker if it's not static. I also don't have an implementation .cpp file.

What should I do, and why is it doing this to me?


Solution

  • static specifier makes compiler create a separate variable for each translation unit. So most likely you call append in one translation unit and then get in another translation unit so they operate on different variables.

    Given that you can use modern compiler you can mark variable as inline:

    inline std::vector<T> vec;
    

    Or, even better, wrap it along with the functions into class and use as private static class field.