How to have static data members in a header-only library?

后端 未结 3 965
走了就别回头了
走了就别回头了 2020-11-29 08:04

What is the best way to have a static member in a non-templated library class, without placing the burden of defining the member on the class user?

Say I want to pro

3条回答
  •  生来不讨喜
    2020-11-29 08:43

    C++17 and above

    Use inline static variables for non-dynamic initialization:

    struct Foo
    {
        inline static int I = 0;
    };
    

    And use function local static variables otherwise:

    struct Foo
    {
        static std::string& Bar()
        {
            static std::string S = compute();
            return S;
        }
    };
    

    C++14 and below

    Use function local statics, as they are plain easier to use.

    If for some reason you really wish for a static data member, then you can use the template trick:

    template 
    struct Foo
    {
         static int I = 0; // inline initialization only for simple types.
    };
    
    template 
    int Foo::I;
    

    On local statics

    For resources which require dynamic initialization, it is best to use a local static.

    The order in which file-scope or class-scope statics are dynamically initialized is undefined, in general, leading to the Static Initialization Order Fiasco when you try to read a uninitialized static as part of the initialization of another. Local static solve the issue by being initialized lazily, on first use.

    There is some slight overhead to using local statics, however. From C++11 onwards, the initialization is required to be thread-safe, which typically means that any access is gated by an atomic read and well-predicted branch.

提交回复
热议问题