June 2025
Intermediate to advanced
1093 pages
33h 24m
English
Similar, but not the same, is the use of static with local variables—that is, within a function. When you add static to the declaration of a local variable, this variable persists when the program flow leaves the scope and is reused when it is entered again.
// https://godbolt.org/z/h5qond6db#include <iostream> // coutclass Keyboard { Keyboard(const Keyboard&) = delete; // no copy const size_t nr_; // current numberpublic: static inline size_t count_ = 0; // counts created instances explicit Keyboard() : nr_{count_++} { std::cout << " Keyboard().nr:"<<nr_<<"\n"; }};Keyboard& getKeyboard() { std::cout << " getKeyboard()\n"; static Keyboard keyboard{}; // static local variable return keyboard;}void func() { std::cout ...
Read now
Unlock full access