Initialization of Private Static Data Members: Alternative to Static Constructors
It is common to encounter a need for private static data members in a class, similar to the Java or C# concept of static constructors. However, C does not provide an explicit mechanism for static constructors.
To address this issue, C offers an alternative approach. Instead of declaring static data members within the class, create a separate ordinary class to hold the static data. Declare a static instance of this ordinary class within the desired class.
For example:
class StaticStuff { std::vector<char> letters_; public: StaticStuff() { for (char c = 'a'; c <= 'z'; c++) letters_.push_back(c); } // Provide a method to access letters_ }; class Elsewhere { static StaticStuff staticStuff; // Static instance runs once };
By using this technique, the static data is initialized once during the program execution and can be accessed throughout the program's lifetime. This approach serves as a viable alternative to static constructors in C .
The above is the detailed content of How to Initialize Private Static Data Members in C Without Static Constructors?. For more information, please follow other related articles on the PHP Chinese website!