C++中的静态构造函数?我需要初始化私有静态对象

我想要一个带有私有静态数据成员的类(一个包含所有字符 a-z 的向量).在 java 或 C# 中,我可以只创建一个静态构造函数",它会在我创建类的任何实例之前运行,并设置类的静态数据成员.它只运行一次(因为变量是只读的并且只需要设置一次)并且因为它是类的函数,所以它可以访问其私有成员.我可以在构造函数中添加代码来检查向量是否已初始化,如果未初始化则对其进行初始化,但这会引入许多必要的检查并且似乎不是问题的最佳解决方案.

I want to have a class with a private static data member (a vector that contains all the characters a-z). In java or C#, I can just make a "static constructor" that will run before I make any instances of the class, and sets up the static data members of the class. It only gets run once (as the variables are read only and only need to be set once) and since it's a function of the class it can access its private members. I could add code in the constructor that checks to see if the vector is initialized, and initialize it if it's not, but that introduces many necessary checks and doesn't seem like the optimal solution to the problem.

我想到,由于变量将是只读的,它们可以只是公共静态常量,所以我可以在类外设置一次,但再一次,这似乎有点像一个丑陋的黑客.

The thought occurs to me that since the variables will be read only, they can just be public static const, so I can set them once outside the class, but once again, it seems sort of like an ugly hack.

如果我不想在实例构造函数中初始化它们,是否可以在类中拥有私有静态数据成员?

推荐答案

要获得等效的静态构造函数,您需要编写一个单独的普通类来保存静态数据,然后创建该普通类的静态实例.

To get the equivalent of a static constructor, you need to write a separate ordinary class to hold the static data and then make a static instance of that ordinary class.

class StaticStuff
{
     std::vector<char> letters_;

public:
     StaticStuff()
     {
         for (char c = 'a'; c <= 'z'; c++)
             letters_.push_back(c);
     }

     // provide some way to get at letters_
};

class Elsewhere
{
    static StaticStuff staticStuff; // constructor runs once, single instance

};

相关文章