Menu

How to deal with passByValue (CWE: 398) warnings?

2025-01-08
2025-01-09
  • Niels Dekker

    Niels Dekker - 2025-01-08

    First of all, thanks for your great tool, Daniel! I'm involved with ITK and I see that Sean McBride has found some very interesting issues in our code, by using cppcheck: https://github.com/InsightSoftwareConsortium/ITK/pull/5125

    Now honesty I have mixed feelings about some of the passByValue warnings that appear, saying:

    (performance) Function parameter should be passed by const reference.

    When an object is trivially copyable, I feel that pass-by-value is very reasonable. It may even be preferred in such case.

    How does cppcheck decide for which types it produces those warnings? And how would you work around them, in cases when they appear undeserved?

     
  • CHR

    CHR - 2025-01-08

    The heuristic is 'larger than two pointers'.
    However, in your case the size computation is incorrect. Please refer to https://trac.cppcheck.net/ticket/13537

     
    👍
    1
  • Niels Dekker

    Niels Dekker - 2025-01-08

    Thank you @CHR

    Note that the warning even appears for S<char, 1>, whose size is typically only 1 byte:

    void f(S<char, 1> s) {} // cppcheck 2.16.0 passByValue warning

     
  • Oliver Stöneberg

    Also the solution given in the message is misleading. The solution might not be using a const reference but moving the object in question - see https://trac.cppcheck.net/ticket/12384.

     
  • Niels Dekker

    Niels Dekker - 2025-01-09

    @Oliver Good point. Of course, the solution of moving the object does not apply to trivially copyable object types. Is cppcheck technically able to estimate whether a type is trivially copyable?

    As @CHR already observerd at https://trac.cppcheck.net/ticket/13537 , those "undeserved" passbyValue warning only appear on template instantiations. They don't appear on a simple small non-templated struct like the following:

    struct T {
      int a[3];
    };
    
    void f(T t) {} // OK: no passbyValue warning
    
     

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.