MISRA C++:2023 Rule 15.1.5
A class shall only define an initializer-list constructor when it is the only constructor
Since R2024b
Description
Rule Definition
A class shall only define an initializer-list constructor when it is the only constructor. 1
Rationale
If a class contains a constructor that takes a parameter of type
std::initializer_list
and another constructor with parameters, braced
initializations such as:
classType obj {0,1}
std::initializer_list
parameter, but developers might expect
otherwise.Polyspace Implementation
The checker flags class definitions that contain a constructor whose first parameter is
of type std::initializer_list
and also contains another constructor
(excluding the special member function constructors). The rule violation is followed by
events that point to the location of the other constructors that might lead to confusion
with the std::initializer_list
constructor.
A class definition with an std::initializer_list
-parameter
constructor that does not violate this rule has only the default, copy and move constructors
(and copy and move assignment operators). If you cannot avoid a second constructor with
parameters, you can justify this rule violation. In that case, for initializing with a list,
use a syntax such as:
classType obj ({0,1})
std::initializer_list
-parameter constructor is invoked.
For initializing with the other constructors, use a syntax such
as:classType obj (0,1)
()
, but allows
such initializations for classes with a mix of
std::initializer_list
-parameter constructor and other
constructors.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: Special member functions |
Category: Required |
Version History
Introduced in R2024b
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.