AutosarC++17_03-A12.1.3¶
If all user-defined constructors of a class initialize data members with constant values that are the same across all constructors, then data members shall be initialized using NSDMI instead
Required inputs: IR
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | automated |
Rationale
Using NSDMI lets the compiler to generate the function that can be more efficient than a user-defined constructor that initializes data member variables with pre-defined constant values.
Example
// $Id: A12-1-3.cpp 271696 2017-03-23 09:23:09Z piotr.tanski $
#include <cstdint>
#include <string>
class A {
public:
A()
: x(0), y(0.0F), str() // Non-compliant
{}
// ...
private:
std::int32_t x;
float y;
std::string str;
};
class B {
public:
// ...
private:
std::int32_t x = 0; // Compliant
float y = 0.0F; // Compliant
std::string str = ""; // Compliant
};
class C {
public:
C()
: x(0), y(0.0F), str() // Compliant
{}
C(std::int32_t i, float f, std::string s)
: x(i), y(f), str(s) // Compliant
{}
// ...
private:
std::int32_t x =
0; // Non-compliant - there’s a constructor that initializes C
// class with user input
float y = 0.0F; // Non-compliant - there’s a constructor that initializes C
// class with user input
std::string str = ""; // Non-compliant - there’s a constructor that
// initializes C class with user input
};
See Also
- C++ Core Guidelines [10]: C.45: Don’t define a default constructor that only initializes data members; use in-class member initializers instead.
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
use_nsdmi |
Use NSDMI for common constant initializations ({}). |
None |
False |
Options¶
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
allow_constructors_of_types¶
allow_constructors_of_types : set[bauhaus.analysis.config.QualifiedName] = set()
allow_literal_like_constructors¶
allow_literal_like_constructors : bool = False
min_number_common_inits¶
min_number_common_inits : int = 1