3.3 Storage duration

3.3.1 Do not use variables with static storage duration

Variables with linkage (and hence static storage duration), commonly referred to as global variables, can be accessed and modified from anywhere in the translation unit if they have internal linkage, and anywhere in the program if they have external linkage. This can lead to uncontrollable relationships between functions and modules. Additionally, certain aspects of the order of initialization of global variables are unspecified and implementation defined in the C++ Language Standard. This can lead to unpredictable results for global variables that are initialized at run-time (dynamic initialization). This rule does not prohibit use of a const object with linkage, so long as:

  • it is initialized through static initialization
  • the object is not ODR used
#include <cstdint>
               
static int32_t foo ();
extern int32_t ga (foo ()); // @@- Non-Compliant -@@
extern int32_t gb (ga);     // @@- Non-Compliant -@@
               
namespace 
{
int32_t la (0);           // @@- Non-Compliant -@@
const int32_t SIZE (100); // @@+ Compliant +@@
}

The order of initialization of block scope objects with static storage duration is well defined. However, the lifetime of such an object ends at program termination, which may be incompatible with future uses of the code, e.g. as a shared library. It is preferable to use objects with dynamic storage duration to represent program state, allocated from the heap or a memory pool.

class Application
{
// ...
};
     
Application const & theApp()
{
static Application app; // @@- Non-Compliant -@@
return app;
}

References

  • HIC++ v3.3 – 8.2.2

Click here for references