Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c++ - What are static variables?

What are static variables designed for? What's the difference between static int and int?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The static keyword has four separate uses, only two of which are closely related:

  • static at global and namespace scope (applied to both variables and functions) means internal linkage
    • this is replaced by unnamed namespaces and is unrelated to the rest
    • in particular, others tend to imply some sort of uniqueness, but internal linkage means the opposite: you can have many objects with the same name, as long as each has internal linkage and you only have one per translation unit
  • static data members are "shared" among all instances of the class
    • it's more like they are independent of any class instance
    • this is sometimes grouped with static methods
  • static methods do not "operate" on a current instance
    • no this pointer; can call without an instance
  • static local variables (in functions) persist across the scope of each function call

Both static data members and static local variables can become hidden global state, and should be used carefully.

Now which two are closely related? It's not the two class members—the warning about global state gives it away. You can consider static data members as static local variables, where the functions to which they belong are all methods of the class, instead of a single function.

I found many related questions, but, surprisingly, no duplicates.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...