Why Doesn't G++ Warn About Unused Result of Const Member?

74 views Asked by At

I am very much annoyed about a stupid mistake that I have made. But I am even annoyed more about my compiler (g++ 8.1) that didn't warn me. ;-)

Please consider the following code:

class Test
{
public:

    int getNumber() const
    {
        return 3;
    }
};

int main(void)
{
    Test test;
    test.getNumber();

    return 0;
}

In my opinion the line

test.getNumber();

is definitely wrong. A const member of Test is called, but the return value is not used. Even though I have been compiling with -Wall -Wextra g++ refused to issue a warning. I have checked the documentation of -Wunused-result. If I add the attribute __attribute__ ((warn_unused_result)) to the member, then the compiler will indeed warn me.

But why is this necessary? Isn't ignoring the return value of a const method always wrong? And shouldn't I have the possibility to set the warn_unused_result attribute automatically for all const members?

I am very much excited about your answers.

1

There are 1 answers

5
Bathsheba On BEST ANSWER

No not in full generality.

  1. There could be mutable members in the class. Granted the compiler could check that.

  2. The const method might have other side effects (writing to the console for example), which would be difficult to detect if the function implementation was in a different translation unit.