#include <iostream>
struct SideEffectTracker {
int name;
explicit SideEffectTracker(int tag) : name(tag) {
std::cout << "[CONSTRUCTOR] " << name << " initialized.\n";
}
~SideEffectTracker() {
std::cout << "[DESTRUCTOR] " << name << " destroyed.\n";
}
void touch() const {
std::cout << "[USAGE] " << name << " accessed.\n";
}
};
// 1. Global statics (Initialized before main() in order of declaration)
SideEffectTracker g_global1(1);
SideEffectTracker g_global2(2);
void run_local_statics() {
// 2. Function-local static (Lazy initialization: only runs on first call)
static SideEffectTracker s_local_static(3);
s_local_static.touch();
}
int main() {
std::cout << "=== Entering main() ===\n\n";
g_global1.touch();
std::cout << "\n-- First call to run_local_statics() --\n";
run_local_statics();
std::cout << "\n-- Second call to run_local_statics() --\n";
run_local_statics();
std::cout << "\n=== Exiting main() ===\n";
return 0;
// Static destructors run after this line in REVERSE order of construction
}
should print:
[CONSTRUCTOR] 1 initialized.
[CONSTRUCTOR] 2 initialized.
=== Entering main() ===
[USAGE] 1 accessed.
-- First call to run_local_statics() --
[CONSTRUCTOR] 3 initialized.
[USAGE] 3 accessed.
-- Second call to run_local_statics() --
[USAGE] 3 accessed.
=== Exiting main() ===
[DESTRUCTOR] 3 destroyed.
[DESTRUCTOR] 2 destroyed.
[DESTRUCTOR] 1 destroyed.
should print: