Home>
Contents of question

Static member variable (table1, table2) Static member function to initializeinitialize ()there is.
Now, "Before accessing static member variables, be sure toinitialize ()It says "call once", but if the user forgets to call it and accesses the static member variable, an error will occur.

To prevent this from happening, when the program starts (main ()Before) automaticallyinitialize ()I want to be called to initialize static member variables. Is there a way to do that?

I look forward to working with you.

environment
  • C ++ 17
code

* In the code below, the contents of member variables can be determined at compile time, but the contents cannot be determined at compile time because the process actually reads and initializes the file.

#include 
#include<iostream>
#include<vector>
class MyClass
{
public:
    // Function I want to call when the program starts
    static void initliaze ()
    {
        if (! table1.empty ())
            return;// Initialized
        make_table (table1);
        make_table (table2);
    }
    static void make_table (std :: vector<size_t>&table)
    {
        table.resize (10);
        for (size_t i = 0;i<10;i ++)
            table [i] = i;
    }
    static std :: vector<size_t>table1;
    static std :: vector<size_t>table2;
};
std :: vector<size_t>MyClass :: table1;
std :: vector<size_t>MyClass :: table2;
int main (int, char **)
{
    MyClass :: initliaze ();
    std :: cout<<MyClass :: table1 [3]<<std :: endl;
}
Solutions

Based on what you taught me, I modified it as follows.
Thanks for your answer.

#include 
#include<iostream>
#include<vector>
class MyClass
{
public:
    MyClass ()
    {
        initliaze ();
    }
    // Function I want to call when the program starts
    static void initliaze ()
    {
        if (! table1.empty ())
            return;// Initialized
        make_table (table1);
        make_table (table2);
    }
    static void make_table (std :: vector<size_t>&table)
    {
        table.resize (10);
        for (size_t i = 0;i<10;i ++)
            table [i] = i;
    }
    static std :: vector<size_t>table1;
    static std :: vector<size_t>table2;
};
std :: vector<size_t>MyClass :: table1;
std :: vector<size_t>MyClass :: table2;
static MyClass inst;
int main (int, char **)
{
    std :: cout<<MyClass :: table1 [3]<<std :: endl;
}
c++
  • Answer # 1

    If it's a static instance constructor, I think it can be processed before the main function. Operation unconfirmed.

  • Answer # 2

    public staticIf you want to initialize a variable, how about creating a separate class for initialization and initializing it with its constructor (Qiita)?

Related articles