How to raise warning if return value is disregarded?

后端 未结 8 935
北海茫月
北海茫月 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 04:06

    As far as I'm aware there is no GCC option to give this warning. However, if you are interested in specific functions, you can tag them with an attribute:

    int fn() __attribute__((warn_unused_result));
    

    which would give a warning if the return value of fn() was not used. Caveat: I've never used this feature myself.

    0 讨论(0)
  • 2020-11-27 04:10

    You can use this handy template to do it at run-time.

    Instead of returning an error code (e.g. HRESULT) you return a return_code<HRESULT>, which asserts if it goes out of scope without the value being read. It's not a static analysis tool, but it's useful none the less.

    class return_value
    {
    public:
      explicit return_value(T value)
        :value(value), checked(false)
      {
      }
    
      return_value(const return_value& other)
        :value(other.value), checked(other.checked)
      {
        other.checked = true;
      }
    
      return_value& operator=(const return_value& other)
      {
        if( this != &other ) 
        {
          assert(checked);
          value = other.value;
          checked = other.checked;
          other.checked = true;
        }
      }
    
      ~return_value(const return_value& other)
      {
        assert(checked);
      }
    
      T get_value()const {
        checked = true;
        return value;
      }
    
    private:
      mutable bool checked;
      T value;
    };
    
    0 讨论(0)
提交回复
热议问题