AUTOSAR C++14 Rule A3-3-2
Static and thread-local objects shall be constant-initialized
Description
Rule Definition
Static and thread-local objects shall be constant-initialized.
Rationale
Static and thread-local objects are initialized at the start of code execution. The C++ language standard only partially defines the initialization order of multiple static or thread-local objects and the order can change from build to build. If you initialize a static or thread-local object from another such object, the compiler might access the latter object before it is initialized. To avoid access before initialization, initialize static and thread-local objects by using objects that evaluate to a constant at compile time. Initialization with constants occurs before initialization with variables and often happens at compile time.
This rule applies to global variables, static variables, static class member variables, and static function-scope variables.
Polyspace Implementation
Polyspace® flags initializations of static or thread-local objects using initializers and constructors that do not evaluate to constants at compile time. To constant-initialize static or thread-local objects, use:
A
constexpr
constructor with only constant argumentsA constant expression
A value
Because string objects use dynamic memory allocation of unknown size, the compiler cannot evaluate them at compile time. Polyspace flags initialization of string objects irrespective of whether you specify an initializer.
If the constructor of a class is not constexpr
, then a global,
static, or thread local instance of the class cannot be constant-initialized, resulting in a
violation. For example, in this code, the class myClass
lacks a
constexpr
constructor. Instances of this class that are global,
static
, or thread-local results in
violations:
class myClass { public: myClass() {} //no a constexpr }; namespace { myClass myObject{}; //Noncompliant } // namespace void foo() { static myClass myStaticObject{}; // Noncompliant }
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Basic concepts |
Category: Required, Automated |
Version History
Introduced in R2020a