How to raise warning if return value is disregarded?

后端 未结 8 1024
北海茫月
北海茫月 2020-11-27 03:35

I\'d like to see all the places in my code (C++) which disregard return value of a function. How can I do it - with gcc or static code analysis tool?

Bad code exampl

8条回答
  •  情话喂你
    2020-11-27 03:50

    For C++17 the answer to this question changes since we now have the [[nodiscard]] attribute. Covered in [dcl.attr.nodiscard]:

    The attribute-token nodiscard may be applied to the declarator-id in a function declaration or to the declaration of a class or enumeration. It shall appear at most once in each attribute-list and no attribute-argument-clause shall be present.

    and

    [ Example:

    struct [[nodiscard]] error_info { /* ... */ };
    error_info enable_missile_safety_mode();
    void launch_missiles();
    void test_missiles() {
      enable_missile_safety_mode(); // warning encouraged
      launch_missiles();
    }
    error_info &foo();
    void f() { foo(); }             // warning not encouraged: not a nodiscard call, because neither
                                    // the (reference) return type nor the function is declared nodiscard
    

     — end example ]

    So modifying your example (see it live):

    [[nodiscard]] int f(int z) {
        return z + (z*2) + z/3 + z*z + 23;
    }
    
    
    int main()
    {
      int i = 7;
      f(i); // now we obtain a diagnostic
    
      return 1;
    }
    

    We now obtain a diagnostic with both gcc and clang e.g.

    warning: ignoring return value of function declared with 'nodiscard' attribute [-Wunused-result]
      f(i); // now we obtain a diagnostic
      ^ ~
    

提交回复
热议问题