It would be helpful if sonarsource would suggest to set a constructor as a constexpr constructor when possible. It would allow the constructor to return a value computed at compile time when requested. It wouldn’t break normal usage of the constructor, just allow more usages.
This feature, and the constraints are described here:
Constexpr constructors (C++11) - IBM Documentation
constexpr specifier (since C++11) - cppreference.com
Example of non compliant code:
struct IMAGEHELPER_API Color
{
Color() noexcept = default;
explicit Color(uint16_t g) noexcept
: gray(g) {}
Color(uint16_t g, uint16_t a) noexcept
: gray(g), alpha(a) {}
Color(uint16_t r, uint16_t g, uint16_t b) noexcept
: red(r), green(g), blue(b) {}
Color(uint16_t r, uint16_t g, uint16_t b, uint16_t a) noexcept
: red(r), green(g), blue(b), alpha(a) {}
uint16_t gray = 0;
uint16_t red = 0;
uint16_t green = 0;
uint16_t blue = 0;
uint16_t alpha = 0;
};
That would give the following compliant code:
struct IMAGEHELPER_API Color
{
constexpr Color() noexcept = default;
explicit constexpr Color(uint16_t g) noexcept
: gray(g) {}
constexpr Color(uint16_t g, uint16_t a) noexcept
: gray(g), alpha(a) {}
constexpr Color(uint16_t r, uint16_t g, uint16_t b) noexcept
: red(r), green(g), blue(b) {}
constexpr Color(uint16_t r, uint16_t g, uint16_t b, uint16_t a) noexcept
: red(r), green(g), blue(b), alpha(a) {}
uint16_t gray = 0;
uint16_t red = 0;
uint16_t green = 0;
uint16_t blue = 0;
uint16_t alpha = 0;
};
Example:
std::unique_ptr has a constexpr constructor: