How to raise warning if return value is disregarde

2019-01-05 01:12发布

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 example:

int f(int z) {
    return z + (z*2) + z/3 + z*z + 23;
}


int main()
{
  int i = 7;
  f(i); ///// <<----- here I disregard the return value

  return 1;
}

Please note that:

  • it should work even if the function and its use are in different files
  • free static check tool

8条回答
何必那么认真
2楼-- · 2019-01-05 01:42

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;
};
查看更多
老娘就宠你
3楼-- · 2019-01-05 01:42

Any static analysis code (e.g. PC-Lint) should be able to tell you that. For PC-Lint, I know that this is the case.

查看更多
登录 后发表回答