AutosarC++17_10-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 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#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