• Thread storage duration (C++11)— These days multicore processors are common. These are CPUs that can handle several execution tasks simultaneously. This allows a program to split computations into separate
• Dynamic storage duration— Memory allocated by the new operator persists until it is freed with the delete operator or until the program ends, whichever comes first. This memory has dynamic storage duration and sometimes is termed the
You’ll get the rest of the story now, including fascinating details about when variables of different types are in scope, or visible (that is, usable by the program), and about linkage, which determines what information is shared across files.
Scope and Linkage
A C++ variable can have one of several scopes. A variable that has
C++ functions can have class scope or namespace scope, including global scope, but they can’t have local scope. (Because a function can’t be defined inside a block, if a function were to have local scope, it could only be known to itself and hence couldn’t be called by another function. Such a function couldn’t function.)
The various C++ storage choices are characterized by their storage duration, their scope, and their linkage. Let’s look at C++’s storage classes in terms of these properties. We begin by examining the situation before namespaces were added to the mix and then see how namespaces modify the picture.
Automatic Storage Duration
Function parameters and variables declared inside a function have, by default, automatic storage duration. They also have local scope and no linkage. That is, if you declare a variable called texas in main() and you declare another variable with the same name in a function called oil(), you’ve created two independent variables, each known only in the function in which it’s defined. Anything you do to the texas in oil() has no effect on the texas in main(), and vice versa. Also each variable is allocated when program execution enters the innermost block containing the definition, and each fades from existence when execution leaves that block. (Note that the variable is allocated when execution enters the block, but the scope begins only after the point of declaration.)
If you define a variable inside a block, the variable’s persistence and scope are confined to that block. Suppose, for example, that you define a variable called teledeli at the beginning of main(). Now suppose you start a new block within main() and define a new variable, called websight, in the block. Then, teledeli is visible in both the outer and inner blocks, whereas websight exists only in the inner block and is in scope only from its point of definition until program execution passes the end of the block:
int main()
{
int teledeli = 5;
{ // websight allocated
cout << "Hello\n";
int websight = -2; // websight scope begins
cout << websight << ' ' << teledeli << endl;
} // websight expires
cout << teledeli << endl;
...
} // teledeli expires