Is a bad practice to declare static variables into functions/member functions?

前端 未结 4 1050
小蘑菇
小蘑菇 2021-01-01 20:18

Recently a fellow worker showed to me a code like this:

void SomeClass::function()
{
    static bool init = false;

    if (!init)
    {
        // hundreds          


        
4条回答
  •  难免孤独
    2021-01-01 21:20

    Global state is probably the worst problem here. Other functions don't have to be concerned with it, so it's not an issue. The fact that it can be achieved without static variable essentially means you made some form of a singleton. Which of course introduces all problems that singleton has, like being totally unsuitable for multithreaded environment, for one.

提交回复
热议问题