C++ Nifty Counter idiom; why?

后端 未结 4 550

I recently came across the Nifty Counter Idiom. My understanding is that this is used to implement globals in the standard library like cout, cerr, etc. Since the experts have c

4条回答
  •  太阳男子
    2021-01-31 09:55

    With the solution you have here, the global stream variable gets assigned at some point during static initialization, but it is unspecified when. Therefore the use of stream from other compilation units during static initialization may not work. Nifty counter is a way to guarantee that a global (e.g. std::cout) is usable even during static initialization.

    #include 
    
    struct use_std_out_in_ctor
    {
        use_std_out_in_ctor()
        {
            // std::cout guaranteed to be initialized even if this
            // ctor runs during static initialization
            std::cout << "Hello world" << std::endl;
        }
    };
    
    use_std_out_in_ctor global; // causes ctor to run during static initialization
    
    int main()
    {
        std::cout << "Did it print Hello world?" << std::endl;
    }
    

提交回复
热议问题