Reviewing static in C++. Different uses of the static keyword.
Автор: enigma tutorials
Загружено: 2025-03-29
Просмотров: 348
Here's the main uses of statics in Cpp.
Providing this as a quick reference rather than a deep dive.
Since it can be confusing as to which type of static is being referred to when talking about C++.
Static members are shared across all class/struct instances. (both static functions and static variables can be set without an instance of the object.
Local static variables, are variables declared in a function/block, that are specific to that function.
You can have another function with the same named static variable, but they will be distinct.
Each time a function is called, it can update the static variable for that function.
This is useful for little quick tests for doing things like counting up how many times a function is called.
Or caching some expensive data that is costly to get.
But be warned, these are precarious. They can lead to memory leaks. Like say you grab a pointer address as a static variable. You never delete it. Then it will live for the lifetime of the application.
Or memory stomp situations. Say you grab a pointer and save it in a local static.
Then that pointer is deleted/freed. Your local static will not be aware of this implicitly, you will need to make sure the pointer is still valid somehow. If you don't, your function can use that memory as if it is still valid, creating a memory stomp over memory somewhere else.
Also consider the size of your local static variables, if place a lot of memory, like an c-array, as a local static, you can end up bloating a lot of memory around in various function calls. It may be better to just make a stack array each time so you don't have wasted memory that is mostly unused, unless the functions are called frequently.
So in general, I avoid local statics if I can, as they can easily cause you subtle problems.
And lastly is file statics. Similar to local statics, but on the scope of the cpp file (translation unit).
These are unique for each translation unit.
This can be useful for some sort of config variable where there isn't a clear place for the memory to live. Like no class instance, but a shared set of functions.
You can put a flag there for debugging, and have the set of functions read the variable, and only log information if that variable was set. (just an example off the top of my head).
But similar issues are present here as what I mentioned above with local statics.
Hope that helps,
Доступные форматы для скачивания:
Скачать видео mp4
-
Информация по загрузке: