What is the lifetime of class static variables in C++?

后端 未结 6 715
野的像风
野的像风 2020-12-25 08:31

If I have a class called Test ::

class Test
{
    static std::vector staticVector;
};

when does staticVector ge

6条回答
  •  生来不讨喜
    2020-12-25 09:03

    Simply speaking:
    A static member variable is constructed when the global variables are constructed. The construction order of global variables is not defined, but it happens before the main-function is entered.

    Destruction happens when global variables are destroyed.

    Global variables are destroyed in the reversed order they were constructed; after exiting the main-function.

    Regards,
    Ovanes

    P.S.: I suggest to take a look at C++-Standard, which explains (defines) how and when global or static member variables are constructed or destructed.

    P.P.S.: Your code only declares a static member variable, but does not initialize it. To initialize it you must write in one of the compilation units:

    std::vector Test::staticVector;
    or
    std::vector Test::staticVector=std::vector(/* ctor params here */);

提交回复
热议问题