Global vector emptying itself between calls?

前端 未结 2 1834
鱼传尺愫
鱼传尺愫 2021-01-18 11:44

I have a vector in a header, like so:

extern std::vector g_vector;

In the associated cpp file I have this:

std::         


        
相关标签:
2条回答
  • 2021-01-18 12:13

    Not sure what the issue really is, but I guess the following pattern will help solve it: define an accessor to the global variable and allocate it as a static function variable as shown below.

    In the header file:

    std::vector<Foo> &getGlobalVector();
    

    In the cpp file:

    std::vector<Foo> &getGlobalVector()
    {
      static std::vector<Foo> s_vector;
      return s_vector;
    }
    

    This pattern is inspired from Andrei Alexandrescu's "generic singleton" implementation in Modern C++ design.

    I've taken the habit of systematically using this pattern whenever I fell upon an existing global variable while maintaining existing applications (or in the rare occasions I actually chose to use one myself), and it may have helped in eliminating a couple of hard-to-reproduce bugs in said applications.

    At any rate, this should really help avoiding any multiple-initialization or order-of-initialization related issue.

    0 讨论(0)
  • 2021-01-18 12:17

    Order of initialization of global values is not defined.

    Read here about the static initialization fiasco.

    When you declare Bar in a function - the g_vector will be initialized before, because its promised to be initialized before the program runs. If Bar is a global variable - then you have a problem.

    0 讨论(0)
提交回复
热议问题