Menu

C++ use of explicit suggested by cppcheck

Anna
2021-02-01
2021-02-01
  • Anna

    Anna - 2021-02-01

    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
  • CHR

    CHR - 2021-02-01

    Why don't you write A a{1}; or (more verbose) A a = A{1}?
    Non-explicit constructors get flagged to prevent unwanted conversions.

     
  • Daniel Marjamäki

    yes the reason cppcheck warns is because there can be unwanted conversions. Imagine:

    void foo(A a);
    
    void dostuff(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

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.