static variable in method call

2020-07-14 05:26发布

问题:

If you create a local static variable inside a method, is that initialised once per instance, or once per program?

Does this differ between C++ and Objective-C?

回答1:

If you create a local static variable inside a method, is that initialised once per instance, or once per program?

Once per program.

Even if it is in a non-static class member function, it is not associated with any class instance; there will only be one instance of the variable in the whole program, initialised just once.

Does this differ between C++ and Objective-C?

In C++, it is initialised the first time the function is called. In C (and Objective-C), it is initialised prior to program startup. In practice, this doesn't make a difference, since the initialisation can't have any side effects in C.



回答2:

Be aware that in C++ if your class or method is "templated" then an own static variable will be created for every template instantiation. E.g. using three different template parameter types results in three different static variables.



回答3:

Objective-C is not different from C in that respect, so a local static variable inside a method is initialized just once in a program lifetime.

Have also a look at this S.O. post, which might help with how you use static variables in Obj-C.



回答4:

It's initialized once per program.

It does not vary from ObjC++ to ObjC methods.

It could vary if it were C -- a C function could copy the static data if (for example) the function were a static inline function. Thus, you may end up with redundant static variables.

With C++, it's once per program. Inside a method or exported C function, it's once per program.



回答5:

In C++ it's initialised at most once per program; the initialisation occurs when the method is first executed. (Specifically when the declaration is executed.)



回答6:

You don't have instances of methods at all (at least not in the sense that you can create more of them).

Modulo linker weirdness, you get one copy of each method, and one copy each of any static variables.