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

前端 未结 4 1031
小蘑菇
小蘑菇 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:16

    Adding to what others said, you can't have multiple objects of this class at the same time, or at least would they not behave as expected. The first instance would set the static variable and do the initialization. The ones created later though would not have their own version of init but share it with all other instances. Since the first instance set it to true, all following won't do any initialization, which is most probably not what you want.

提交回复
热议问题