Is using the cast constructor bad? Otherweise why a code quality checker (cppcheck in my case) would constantly suggest to add explicit before single parameter constructors?
yes the reason cppcheck warns is because there can be unwanted conversions. Imagine:
voidfoo(Aa);voiddostuff(A*a){foo(a);}
The function call would do the same thing as : int x = a; A temp(x); foo(temp);. Maybe a compiler will warn about pointer => int conversion not sure.
Cppcheck does not try to detect if there seems to be some mistake it only detects that there is missing explicit keyword.. I do think this is a bit unfortunate. And makes this warning rather noisy.
Well it is your decision. I do not have a strong opinion.. feel free to suppress this warning.
Last edit: Daniel Marjamäki 2021-02-01
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
Is using the cast constructor bad? Otherweise why a code quality checker (cppcheck in my case) would constantly suggest to add explicit before single parameter constructors?
What if I want to do
class MyClass {
A(int) {}
};
A a = 1;
If I follow the "suggestions" and write
class MyClass {
explicit A(int) {}
};
A a = 1;
would throw an error, but if I use the first I'll have a warning that i've to document to pass the code reviews.
Last edit: Anna 2021-02-02
Why don't you write
A a{1};
or (more verbose)A a = A{1}
?Non-explicit constructors get flagged to prevent unwanted conversions.
yes the reason cppcheck warns is because there can be unwanted conversions. Imagine:
The function call would do the same thing as :
int x = a; A temp(x); foo(temp);
. Maybe a compiler will warn aboutpointer => int
conversion not sure.Cppcheck does not try to detect if there seems to be some mistake it only detects that there is missing
explicit
keyword.. I do think this is a bit unfortunate. And makes this warning rather noisy.Well it is your decision. I do not have a strong opinion.. feel free to suppress this warning.
Last edit: Daniel Marjamäki 2021-02-01