Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3727

Global "static" initializers should not be used

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
      None
    • Message:
      Move this "static" initializer into a getter or the function that uses it.
    • Highlighting:
      Hide

      static

      Show
      static
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way, MISRA C++ 2008 recommended
    • Targeted languages:
      C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      30min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      The execution order of static initializers is unspecified when they are in different compilation units (files). Relying on a particular initialization order can have nasty repercussions and should therefore be avoided. Even if the code works now, it could change in the future without notice.

      If you need to use static globals, you should put them inside the function that uses them, or create a getter and declare them inside that getter.

      Noncompliant Code Example

      static const std::string airports[] = {"GVA", "SFO", "CDG"}; // Noncompliant
      

      Compliant Solution

      std::string GetAirportCode(int i) {
        static const std::string airports[] = {"GVA", "SFO", "CDG"};
        return airports[i];
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              jeanchristophe.collet Jean-Christophe Collet (Inactive)
              Votes:
              1 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: