开发者

Do static local variables in a class persist between objects?

class MyClass
{
  static int staticInt;

  void instanceMethod( int param )
  {
    static int parameter = param;
  }
}

Clearly staticInt is shared between all instance of MyClass. But can different instances of MyClass h开发者_StackOverflowave different values of parameter the static local variable within instaceMethod?

Update

What about between program executions? Certainly they could be different in multiple program instances? What defines "scope" there - the execution unit? The c++ runtime?

Update

Thanks - this helped me squash a critical bug. Wish I could accept them all, but I'm going with the first answer with no other criteria.


There is exactly one instance of parameter.

If you want an instance of parameter for each instance of the class, use a nonstatic member variable.


In order to have different values of parameter for different instances you have to make parameter a non-static member of the class.

In your current version all instances will share the same parameter object. All static objects behave exactly the same in that respect. The only thing that depends on the point of declaration is the scope of the name. i.e. the regions where the name is visible. As for the lifetime and the value-retaining properties of the variable - they are always the same. It that respect it is just like a "global" variable, regardless of where you declare it.

In your example, there's no difference between parameter and staticInt when it comes to their value-retaining properties. The only difference is that staticInt is accessible to all members of the class, while parameter is only accessible to instanceMethod method.

The language provides you with no means to create variables whose values persist between program executions. This kind of persistence has to be implemented manually.


Yes, they both persist. They cannot have different values between instances.


the values are not persistent across program execution(between two different invocation of the same program )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜