C++ Storage Classes
A storage class defines the scope (visibility) and lifetime of variables/functions in a C++ program. These specifiers are placed before the type they modify. The following lists the storage classes available in C++ programs:
-
auto: This is the default storage class specifier and is usually omitted. A variable specified as auto has automatic storage duration, meaning its lifetime is limited to the block in which it is defined. auto variables are usually allocated on the stack.
-
register: Used to suggest the compiler to store the variable in a CPU register to improve access speed. In C++11 and later versions, register is a deprecated feature and no longer has any practical effect.
-
static: Used to define variables or functions with static storage duration; their lifetime spans the entire program execution. Inside a function, the value of a static variable is preserved between function calls. In file scope or global scope, a static variable has internal linkage and can only be accessed in the file where it is defined.
-
extern: Used to declare variables or functions with external linkage, which can be shared across multiple files. By default, global variables and functions have the extern storage class. Declaring a global variable or function defined in another file using extern in one file enables cross-file sharing.
-
mutable (C++11): Used to modify member variables in a class, allowing their values to be modified in const member functions. Usually used for data such as caches or counters that need to be modified in a const context.
-
thread_local (C++11): Used to define variables with thread-local storage duration; each thread has its own independent copy. The lifetime of a thread-local variable is the same as the lifetime of the thread.
Starting from C++17, the auto keyword is no longer a C++ storage class specifier, and the register keyword is deprecated.
The storage class specifiers in provide programmers with a means to control the lifetime and visibility of variables and functions.
Reasonable use of storage class specifiers can improve the maintainability and performance of a program.
Starting from C++11, register has lost its original function, while mutable and thread_local are newly introduced features used to solve specific programming problems.
The following is an example demonstrating different storage class specifiers:
Example
#include
// Global variable, with external linkage, default storage class is extern
int
globalVar
;
void
function
(
)
{
// Local variable, with automatic storage duration, default storage class is auto
auto
int
localVar
=
10
;
// Static variable, with static storage duration, lifetime spans the entire program
static
int
staticVar
=
20
;
const
int
constVar
=
30
;
// const variable has static storage duration by default
// Attempt to modify a const variable, compile error
// constVar = 40;
// mutable member variable, can be modified in const member functions
class
MyClass
{
public
:
mutable
int
mutableVar
;
void
constMemberFunc
(
)
const
{
mutableVar
=
50
;
// Allow modification of mutable member variable
}
}
;
// Thread-local variable, each thread has its own independent copy
thread_local
int
threadVar
=
60
;
}
int
main
(
)
{
extern
int
externalVar
;
// Declare a variable with external linkage
function
(
)
;
return
0
;
}
auto Storage Class
Since C++ 11,auto the keyword is used in two cases: automatically deducing the type of a variable from its initializer expression when declaring a variable, and as a placeholder for the function's return type when declaring a function.
In the C++98 standard, the auto keyword was used to declare automatic variables, but since it was rarely used and redundant, this usage was removed in C++17.
The type of the declared variable is automatically deduced from the initializer expression, for example:
auto
f
=
3
.14
;
//double
auto
s
(
"
hello
"
)
;
//const char*
auto
z
=
new
auto
(
9
)
;
// int*
auto
x1
=
5
,
x2
=
5
.0
,
x3
='
r
';
// Error, must be initialized to the same type
register Storage Class
register is a storage class used to declare variables and suggest to the compiler that these variables be stored in registers for fast access.
Using the register keyword can improve the execution speed of a program because it reduces the number of memory accesses.
However, it should be noted that the register storage class is only a hint; the compiler can ignore it, because modern compilers usually automatically optimize the code and choose an appropriate storage location.
Syntax format:
register data_type variable_name;
registeris the keyword for the storage class, used to suggest the compiler to store the variable in a register.data_typeis the data type of the variable and can be any valid C++ data type.variable_nameis the name of the variable.
void
loop
(
)
{
register
int
i
;
for
(
i
=
0
;
i
<
1000
; ++
i
)
{
// Loop body
}
}
The register storage class is used to suggest the compiler to store variables in registers to improve access speed. However, due to the automatic optimization capabilities of modern compilers, using the register keyword is not necessary and is rarely used in practice.
In the C++11 standard, the register keyword is no longer a storage class specifier but a deprecated feature. This means that in C++11 and later versions, using the register keyword will have no effect on the program.
In C++, references or pointers can be used to improve access speed, especially when dealing with large data structures.
static Storage Class
static The static storage class instructs the compiler to preserve the existence of local variables throughout the lifetime of the program, without creating and destroying them each time they enter and leave scope. Therefore, using static to modify a local variable preserves the value of the local variable between function calls.
The static modifier can also be applied to global variables. When static modifies a global variable, it limits the scope of the variable to the file in which it is declared.
In C++, when static is used on a class data member, it results in only one copy of that member being shared by all objects of the class.
Example
#include
<
iostream
// Function declaration
void
func
(
void
)
;
static
int
count
=
10
;
/*
Global Variables
*/
int
main
(
)
{
while
(
count
--
)
{
func
(
)
;
}
return
0
;
}
// Function definition
void
func
(
void
)
{
static
int
i
=
5
;
// Local static variable
i
++;
std
::
cout
<<
"
Variable i is
"
<<
i
;
std
::
cout
<<
"
, variable count is
"
<<
count
<<
std
::
endl
;
}
When the code above is compiled and executed, it produces the following result:
变量 i 为 6 , 变量 count 为 9
变量 i 为 7 , 变量 count 为 8
变量 i 为 8 , 变量 count 为 7
变量 i 为 9 , 变量 count 为 6
变量 i 为 10 , 变量 count 为 5
变量 i 为 11 , 变量 count 为 4
变量 i 为 12 , 变量 count 为 3
变量 i 为 13 , 变量 count 为 2
变量 i 为 14 , 变量 count 为 1
变量 i 为 15 , 变量 count 为 0
extern Storage Class
extern The extern storage class is used to provide a reference to a global variable, which is visible to all program files. When you use 'extern', for variables that cannot be initialized, the variable name is pointed to a previously defined storage location.
When you have multiple files and define a global variable or function that can be used in other files, you can use extern in other files to get a reference to the already-defined variable or function. It can be understood as follows:extern is used to declare a global variable or function in another file.
The extern modifier is usually used when two or more files share the same global variable or function, as shown below:
First file: main.cpp
Example
#include
<
iostream
int
count;
extern
void
write_extern
(
)
;
int
main
(
)
{
count
=
5
;
write_extern
(
)
;
}
Second file: support.cpp
Example
#include
<
iostream
extern
int
count;
void
write_extern
(
void
)
{
std
::
cout
<<
"
Count is
"
<<
count
<<
std
::
endl
;
}
Here, the extern keyword is used to declare count, which is already defined in the first file main.cpp. Now, compile these two files, as shown below:
$ g++ main.cpp support.cpp -o write
This produces write executable program; try executing write, and it produces the following result:
$ ./write
Count is 5
mutable Storage Class
mutable is a keyword used to modify member variables of a class, allowing them to be modified in const member functions. Normally, a const member function cannot modify the state of the object, but if a member variable is declared as mutable, it can be modified in a const function.
Characteristics:
- Allows modification of:
mutablemember variables can be modified withinconstmember functions. - Design Purpose: Usually used in scenarios that require state management without changing the external state of the object, such as caching, lazy computation, etc.
Example
#include
class
Example
{
public
:
Example
(
)
:
value
(
0
)
, cachedValue
(
0
)
{
}
// Const member function
int
getValue
(
)
const
{
return
value
;
// Read const member
}
// Modify mutable member
void
increment
(
)
{
++
value
;
cachedValue
=
value
2
;
// Modify mutable member
}
int
getCachedValue
(
)
const
{
return
cachedValue
;
// Read mutable member
}
private
:
int
value
;
// Regular member, cannot be modified in const function
mutable
int
cachedValue
;
// Modifiable member, can be modified in const function
}
;
int
main
(
)
{
const
Example ex
;
// ex.increment(); // Error: cannot call a non-const function on a const object
// ex.value = 10; // Error: cannot modify a member of a const object
std
::
cout
<<
"Value: "
<<
ex.
getValue
(
)
<<
std
::
endl
;
std
::
cout
<<
"Cached Value: "
<<
ex.
getCachedValue
(
)
<<
std
::
endl
;
// Output is 0
return
0
;
}
Applicable Scenarios:
- Caching: In
constCompute and cache results in a function without affecting the external state of the object. - State Tracking: Such as a log counter, tracking information such as the number of calls, avoiding intrusive modifications to the class's logic.
Notes:
mutableThe use of variables should be cautious to avoid unexpected state changes that affect the readability and maintainability of the code.mutableApplicable to situations that require changes to state inconstenvironment; rather than a general design pattern.
thread_local Storage Class
thread_local is a storage class introduced in C++11, used to manage thread-specific variables in a multithreaded environment.
A variable modified with thread_local has an independent instance in each thread, so each thread's operations on the variable do not affect other threads.
- Independence: Each thread has its own independent copy of the variable, and read/write operations between different threads do not interfere with each other.
- Lifetime:
thread_localvariable is automatically destroyed when its thread ends. - Initialization:
thread_localvariable can be statically or dynamically initialized, and supports initialization at declaration.
thread_local is suitable for scenarios that need to store thread state, caching, or avoid data races, such as thread pools, request contexts, etc.
The following demonstrates variables that can be declared as thread_local:
#include
<
iostream
#include
<
thread
thread_local
int
threadSpecificVar
=
0;
// Each thread has its own threadSpecificVar
void
threadFunction
(
int
id
)
{
threadSpecificVar
=
id
;
// Set the thread-specific variable
std
::
cout
<<
"
Thread
"
<<
id
<<
"
: threadSpecificVar =
"
<<
threadSpecificVar
<<
std
::
endl
;
}
int
main
(
)
{
std
::
thread
t1
(
threadFunction
,
1
)
;
std
::
thread
t2
(
threadFunction
,
2
)
;
t1
.
join
(
)
;
t2
.
join
(
)
;
return
0
;
}
Notes:
- Performance: Since each thread has an independent copy,
thread_localvariable access may be slightly slower than global or static variables. - Static Storage:
thread_localvariable has static storage duration, so it persists throughout the entire program execution.