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:
-
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
- is related to
-
CPP-1459 Proposed C++ Rule: avoid global static initializers
-
- Open
-