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
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.
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;
};