Is there a static variable inside the constructor that has any flaws or side effects?

What I want to do: run some pre-code when the class instance is used inside the program. This code checks requiremts, etc. And it should be launched only once.

I found that this can be achieved using another object as a static variable inside the constructor. Here is an example of a better image:

class Prerequisites
{
     public:
         Prerequisites() {
              std::cout << "checking requirements of C, ";
              std::cout << "registering C in dictionary, etc." << std::endl;
         }
};


class C
{
    public:
         C() {
             static Prerequisites prerequisites;
             std::cout << "normal initialization of C object" << std::endl;
         }
};

What bothers me is that I have not yet seen a similar use of static variables. Are there any flaws or side effects, or am I missing something? Or maybe there is a better solution? Any suggestions are welcome.

+3
3

, C , , , .

, , , , (.. "" , ).

+5

, - ? , , ? .

( ) .

class Prerequisites
{
    static bool checkedOnce;    
public:
    static void checkOnce() {
        if (checkedOnce)
        {
            //already checked: don't check again
            return;
        }
        //else check them now
        checkedOnce = true;
        std::cout << "checking requirements of C, ";
        std::cout << "registering C in dictionary, etc." << std::endl;
    }
};

bool Prerequisites::checkedOnce = false;

class C
{
public:
    C() {
        Prerequisites::checkOnce();
        std::cout << "normal initialization of C object" << std::endl;
    }
};
+4

At the very least, you should use the mutex and static flag inside the Prerequisites class to protect the reinitialization of Prerequisites. This way your code will become thread safe.

+1
source

Source: https://habr.com/ru/post/1747703/


All Articles