AutosarC++17_03-A12.1.4

All constructors that are callable with a single argument of fundamental type shall be declared explicit

Required inputs: IR

Rationale

The explicit keyword prevents the constructor from being used to implicitly convert a fundamental type to the class type.

See: Fundamental-Types.

Example
// $Id: A12-1-4.cpp 271715 2017-03-23 10:13:51Z piotr.tanski $
#include <cstdint>
class A {
public:
explicit A(std::int32_t number) : x(number) {} // Compliant
A(A const &) = default;
A(A &&) = default;
A &operator=(A const &) = default;
A &operator=(A &&) = default;

private:
std::int32_t x;
};
class B {
public:
B(std::int32_t number) : x(number) {} // Non-compliant
B(B const &) = default;
B(B &&) = default;
B &operator=(B const &) = default;
B &operator=(B &&) = default;

private:
std::int32_t x;
};
void f1(A a) noexcept {}
void f2(B b) noexcept {}
void f3() noexcept {
f1(A(10));
// f1(10); // Compilation error - because of explicit constructor it is not
// possible to implicitly convert integer
// to type of class A
f2(B(20));
f2(20); // No compilation error - implicit conversion occurs
}
See Also
  • MISRA C++ 2008 [6]: Rule 12-1-3 (Required) All constructors that are callable with a single argument of fundamental type shall be declared explicit.

Possible Messages

Key

Text

Severity

Disabled

constructor_missing_explicit

Constructor shall be declared explicit

None

False

Options

consider_only_fundamental_types

consider_only_fundamental_types : bool = True

Whether this check should be limited to single arguments of fundamental type or should also be applied to user defined types.
 

suppress_conditionally_explicit

suppress_conditionally_explicit : bool = True

If enabled, automatically suppress violations for constructors declared conditionally explicit