AutosarC++17_03-A12.6.1¶
All class data members that are initialized by the constructor shall be initialized using member initializers
Required inputs: IR
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | automated |
Rationale
Using the constructor’s member initializers is more efficient than assigning a copy of passed values to data members in the constructor’s body. Also, it supports the programmer to prevent “data usage before initialization” errors.
Note that if a data member is already initialized using member initializer, then changing its value in the constructor’s body does not violate this rule.
Example
// $Id: A12-6-1.cpp 271696 2017-03-23 09:23:09Z piotr.tanski $
#include <cstdint>
#include <string>
class A {
public:
A(std::int32_t n, std::string s)
: number{n}, str{s} // Compliant
{}
// Implementation
private:
std::int32_t number;
std::string str;
};
class B {
public:
B(std::int32_t n, std::string s) // Non-compliant - no member initializers
{
number = n;
str = s;
}
// Implementation
private:
std::int32_t number;
std::string str;
};
class C {
public:
C(std::int32_t n, std::string s)
: number{n}, str{s} // Compliant
{
n += 1; // This does not violate the rule
str.erase(str.begin(), str.begin() + 1); // This does not violate the rule
}
// Implementation
private:
std::int32_t number;
std::string str;
};
See Also
- C++ Core Guidelines [10]: C.49: Prefer initialization to assignment in constructors.
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
implicit_field_init |
Field is only implicitly initialized in constructor. |
None |
False |
missing_field_init |
Field is not initialized in constructor. |
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
exclude_aggregates¶
exclude_aggregates : bool = False
init_functions¶
init_functions : set[bauhaus.analysis.config.FunctionName] = {'Init', 'init'}
inspect_directly_called_methods¶
inspect_directly_called_methods : bool = False
only_member_initializer_list¶
only_member_initializer_list : bool = True
report_missing_field_constructors¶
report_missing_field_constructors : bool = True