20.3. Storage Class

[ fromfile: scopestorage.xml id: storageclass ]

Whenever an object is created, space is allocated in one of four possible places. Each of these places is called a storage class.

[Note]Note

Scope refers to a region of code where an identifier is accessible. Storage class refers to a location in memory.

  1. The static area – Global variables, static locals, and static data members are all stored in the static storage area. The lifetime of a static object begins when its object module loads and ends when the program terminates.

    Used often for pointers, simple types, and string constants, less often for complex objects.

  2. The program stack (automatic storage – auto[115]) – Function parameters, local variables, return values, and other temporary objects are all stored on the stack. Stack storage is allocated automatically when an object definition is executed. Objects in this storage class are local to a function or a block of statements.[116] For local (block-scope) variables, the lifetime is determined by the braces around the code that is executed.

  3. The heap or free storage (dynamic storage) – Objects created via new. The lifetime of a heap object is determined entirely by the use of new and delete.

    In general, the allocation and freeing of heap objects should be kept inside carefully encapsulated classes.

  4. Another storage class, left over from C, is called register. It is a specialized form of automatic storage that consists of a relatively small quantity of the fastest memory available – usually located on the CPU.

    This category of storage can be requested by using the keyword, register in the variable declaration. Most C++ compilers ignore this keyword and put such variables on the stack but possibly with higher priority for access to register memory. Requesting this storage class for an object means that you cannot take its address with the address-of operator (&).



[115] The optional keyword auto is almost never used.

[116] Or a member of another object that is.