Memory Allocation for Static Variables
How does marking a variable as static
impact memory allocation?
Marking a variable as static
in C++ affects its memory allocation by changing its storage duration and scope.
Non-Static Variables
- Storage Duration: Automatic (local variables) or dynamic (heap allocation).
- Scope: Limited to the instance of the class.
- Memory Allocation: Each instance of the class gets its own memory allocation for non-static variables.
For example:
#include <string>
class Vampire {
public:
int Health{100};
};
int main() {
Vampire A;
Vampire B;
// A and B have separate memory for Health
}
Here, A
and B
each have their own Health
variable, stored separately in memory.
Static Variables
- Storage Duration: Static (exists for the lifetime of the program).
- Scope: Shared among all instances of the class.
- Memory Allocation: Only one allocation for the static variable, regardless of the number of instances.
For example:
#include <iostream>
#include <string>
class Vampire {
public:
static inline std::string Faction{"Undead"};
};
int main() {
Vampire A;
Vampire B;
// A and B share the same memory for Faction
}
In this case, Faction
is allocated once and shared by all instances of Vampire
.
Impact on Memory Allocation
- Efficiency: Static variables save memory when the same data is shared among all instances. Instead of each instance having its own copy, a single copy is shared.
- Lifetime: Static variables persist for the lifetime of the program. They are allocated when the program starts and deallocated when the program ends.
- Access: Static variables can be accessed without creating an instance of the class, using the class name and the scope resolution operator
::
.
#include <iostream>
#include <string>
class Vampire {
public:
static inline std::string Faction{"Undead"};
};
int main() {
std::cout << Vampire::Faction << "\n";
Vampire::Faction = "Demonic";
std::cout << Vampire::Faction << "\n";
}
Undead
Demonic
In summary, marking a variable as static
centralizes memory usage for shared data, providing efficient memory management and consistent data access across all instances of the class.
Static Class Variables and Functions
A guide to sharing values between objects using static class variables and functions