方法中的静态局部变量是不好的做法吗? [英] Static local variables in methods a bad practice?

查看:125
本文介绍了方法中的静态局部变量是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在非线程程序中,最好有局部静态变量(方法内部)还是静态类成员? / p>

在此示例中:

  class C {
public :
C(){};
void foo();
};

void C :: foo(){
static int bar = 0;
bar ++;
printf(%d\\\
,bar);
}

如果 bar 将仅用于 C :: foo()

解决方案

两者都更好。它们提供非常不同的用例


there is something that's bugging me.

In a non-threaded program, is it better to have local static variables(inside methods) or static class members?

In this example:

class C{
public: 
  C(){};
  void foo();
};

void C::foo(){
  static int bar = 0;
  bar++;
  printf("%d\n",bar);
}

Is it considered a bad practice if bar will solely be used in C::foo()?

解决方案

Neither is better. They serve very different use cases

这篇关于方法中的静态局部变量是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆