Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

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,

Reviewing static in C++. Different uses of the static keyword.

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Язык Go. Вводный курс для разработчиков

Язык Go. Вводный курс для разработчиков

UHT - Understanding Unreal Header Tool. Exploring C++ generated code - Extended - UE C++ Tutorial

UHT - Understanding Unreal Header Tool. Exploring C++ generated code - Extended - UE C++ Tutorial

Перестаньте мне рассказывать о _Generic

Перестаньте мне рассказывать о _Generic

UHT - Understanding Unreal Header Tool. Exploring C++ generated code - UE C++ Tutorial

UHT - Understanding Unreal Header Tool. Exploring C++ generated code - UE C++ Tutorial

Разблокировка нейросетей (AI) без VPN

Разблокировка нейросетей (AI) без VPN

All the UInterface types explained in Cpp - Unreal Interfaces - UE C++ Tutorial

All the UInterface types explained in Cpp - Unreal Interfaces - UE C++ Tutorial

🤷 AI обучен на говнокоде! Разработчиков компиляторов, протоколов и СУБД не хватает, а LLM не может

🤷 AI обучен на говнокоде! Разработчиков компиляторов, протоколов и СУБД не хватает, а LLM не может

Мессенджер Макс - что с ним не так?

Мессенджер Макс - что с ним не так?

ХИТРОЕ неравенство от составителей ЕГЭ 2026. А ТЫ РЕШИШЬ?!

ХИТРОЕ неравенство от составителей ЕГЭ 2026. А ТЫ РЕШИШЬ?!

Указатели с визуальным объяснением | Кодовые слова

Указатели с визуальным объяснением | Кодовые слова

Принц Персии: разбираем код гениальной игры, вытирая слезы счастья

Принц Персии: разбираем код гениальной игры, вытирая слезы счастья

Роскомнадзор научился блокировать VPN Трафик | Дзен вводит новую валюту на площадке - Стеллы

Роскомнадзор научился блокировать VPN Трафик | Дзен вводит новую валюту на площадке - Стеллы

Алгоритмы и структуры данных за 15 минут! Вместо 4 лет универа

Алгоритмы и структуры данных за 15 минут! Вместо 4 лет универа

ВСЕ поколения DDR памяти: объясняю за 9 минут

ВСЕ поколения DDR памяти: объясняю за 9 минут

Покойся с миром, Arduino и Open Hardware... спасибо Qualcomm

Покойся с миром, Arduino и Open Hardware... спасибо Qualcomm

ОСТАНОВИТЕСЬ. пожалуйста, Microsoft

ОСТАНОВИТЕСЬ. пожалуйста, Microsoft

Русский пост-панк без слов | Russian Doomer Music | Плейлист для вечерних посиделок 4

Русский пост-панк без слов | Russian Doomer Music | Плейлист для вечерних посиделок 4

33 продукта из отходов, которые вы едите каждый день

33 продукта из отходов, которые вы едите каждый день

Декораторы Python — наглядное объяснение

Декораторы Python — наглядное объяснение

Лучший ПК на Windows – это iMac | Старый моноблок Apple vs мини-ПК на N100

Лучший ПК на Windows – это iMac | Старый моноблок Apple vs мини-ПК на N100

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]