Home > Backend Development > C++ > body text

How to Initialize Private Static Data Members in C Without Static Constructors?

Patricia Arquette
Release: 2024-11-10 18:06:02
Original
421 people have browsed it

How to Initialize Private Static Data Members in C   Without Static Constructors?

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
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template