What is a static constructor?

后端 未结 13 1694
天涯浪人
天涯浪人 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:00

    I think static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced. In++, we dont have anything called static constructor but you can mimic the functionality of the static constructor. Take a look at this C# static constructor:

    public class Bus  {
         // Static variable used by all Bus instances.
         // Represents the time the first bus of the day starts its route.
         protected static readonly DateTime globalStartTime;
    
         // Property for the number of each bus.
         protected int RouteNumber { get; set; }
    
         // Static constructor to initialize the static variable.
         // It is invoked before the first instance constructor is run.
         static Bus()
         {
             globalStartTime = DateTime.Now;
    
             // The following statement produces the first line of output, 
             // and the line occurs only once.
             Console.WriteLine("Static constructor sets global start time to {0}",
                 globalStartTime.ToLongTimeString());
         }
    
         // Instance constructor.
         public Bus(int routeNum)
         {
             RouteNumber = routeNum;
             Console.WriteLine("Bus #{0} is created.", RouteNumber);
         }
    
         // Instance method.
         public void Drive()
         {
             TimeSpan elapsedTime = DateTime.Now - globalStartTime;
    
             // For demonstration purposes we treat milliseconds as minutes to simulate
             // actual bus times. Do not do this in your actual bus schedule program!
             Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",
                                     this.RouteNumber,
                                     elapsedTime.Milliseconds,
                                     globalStartTime.ToShortTimeString());
         }  }
    
     class TestBus  {
         static void Main()
         {
             // The creation of this instance activates the static constructor.
             Bus bus1 = new Bus(71);
    
             // Create a second bus.
             Bus bus2 = new Bus(72);
    
             // Send bus1 on its way.
             bus1.Drive();
    
             // Wait for bus2 to warm up.
             System.Threading.Thread.Sleep(25);
    
             // Send bus2 on its way.
             bus2.Drive();
    
             // Keep the console window open in debug mode.
             System.Console.WriteLine("Press any key to exit.");
             System.Console.ReadKey();
         }  }  /* Sample output:
         Static constructor sets global start time to 3:57:08 PM.
         Bus #71 is created.
         Bus #72 is created.
         71 is starting its route 6.00 minutes after global start time 3:57 PM.
         72 is starting its route 31.00 minutes after global start time 3:57 PM.      
    */
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-11-27 04:03

    In C++, there is no static constructor. In C# (and probably in Java too), you can define static constructor which is called automatically by the runtime so as to initialize static members.

    For further question and interest you can read this topic:

    What is the rationale for not having static constructor in C++?

    0 讨论(0)
  • 2020-11-27 04:03

    A static constructor is used to initialize static data of a class. C++ doesn't have static constructor. But a static constructor can be emulated by using a friend class or nested class as below.

    class ClassStatic{
    private:
        static char *str;
    public:
        char* get_str() { return str; }
        void set_str(char *s) { str = s; }
        // A nested class, which used as static constructor
        static class ClassInit{
        public:
            ClassInit(int size){ 
                // Static constructor definition
                str = new char[size];
                str = "How are you?";
            }
        } initializer;
    };
    
    // Static variable creation
    char* ClassStatic::str; 
    // Static constructor call
    ClassStatic::ClassInit ClassStatic::initializer(20);
    
    int main() {
        ClassStatic a;
        ClassStatic b;
        std::cout << "String in a: " << a.get_str() << std::endl;
        std::cout << "String in b: " << b.get_str() << std::endl;
        a.set_str("I am fine");
        std::cout << "String in a: " << a.get_str() << std::endl;
        std::cout << "String in b: " << b.get_str() << std::endl;
        std::cin.ignore();
    }
    

    Output:

    String in a: How are you?
    String in b: How are you?
    String in a: I am fine
    String in b: I am fine
    
    0 讨论(0)
  • 2020-11-27 04:07

    In C++, if someone says "static constructor", they are generally referring to "static initialization" (and destruction). It's not uncommon to use this terminology.

    0 讨论(0)
  • 2020-11-27 04:07

    Here is the simplest static constructor in c++17:

    #include <iostream>
    class h {
        public:
        static inline int i;
        private:
        struct constructor {
            constructor() {
             i=3;
            }
        };
        static inline constructor cons;
    };
    
    int main() {
      std::cout << h::i;
    }
    
    0 讨论(0)
提交回复
热议问题