What is a static constructor?

后端 未结 13 1810
天涯浪人
天涯浪人 2020-11-27 03:46

This question was asked to me in an interview:

What is a static constructor?

Does it exist in C++? If yes, please explain it wit

13条回答
  •  一生所求
    2020-11-27 04:02

    C++ doesn’t have static constructors but you can emulate them using a static instance of a nested class.

    class has_static_constructor {
        friend class constructor;
    
        struct constructor {
            constructor() { /* do some constructing here … */ }
        };
    
        static constructor cons;
    };
    
    // C++ needs to define static members externally.
    has_static_constructor::constructor has_static_constructor::cons;
    

提交回复
热议问题