Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Storage Classes

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:

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;

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:

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:

Notes:

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.

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: