Global vector emptying itself between calls?

前端 未结 2 1835
鱼传尺愫
鱼传尺愫 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 &getGlobalVector();
    

    In the cpp file:

    std::vector &getGlobalVector()
    {
      static std::vector 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.

提交回复
热议问题