Home > Article > Backend Development > How to Simulate Static Constructors in C ?
Static Initialization in C : An Alternative to Static Constructors
In C , initializing private static data members can pose a challenge due to the lack of static constructors. However, there is an elegant solution that mirrors the functionality of static constructors in other languages.
Using a Separate Class
To simulate static initialization, create a separate ordinary class to hold the static data and declare a static instance of this class within the class that requires it. For example:
// StaticStuff class holds static data class StaticStuff { std::vector<char> letters_; public: // Constructor initializes data StaticStuff() { for (char c = 'a'; c <= 'z'; c++) letters_.push_back(c); } // Provide access to static data std::vector<char>& letters() { return letters_; } }; // Class that uses static data class C { // Static instance of StaticStuff (initialized once) static StaticStuff staticStuff; };
In this example, StaticStuff holds the static data letters_, and its constructor initializes it upon the first instantiation. The static instance staticStuff is declared within C, providing access to the static data from within the C class.
Advantages
This approach offers several benefits:
The above is the detailed content of How to Simulate Static Constructors in C ?. For more information, please follow other related articles on the PHP Chinese website!