Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a "statement has no effect" warning on overloaded==

In the following example:

class Test

{
public:
    Test(int _value) { value = _value; };
    const bool operator==(int _value) const { return value == _value; };
private:
    int value;
};

int main(void)
{
    int a;
    a == 1;

    Test b(1);
    b == 1;

    return 0;
}

compilation gives the following:

$ g++ -Wall -pedantic -o test test.cc
a.cc: In function ‘int main()’:
a.cc:13:7: warning: statement has no effect [-Wunused-value]
     a == 1;
     ^

This is good as it has warned that I have made an error and mistyped == for =

But the same is true for my Test class. How can I mark up the class or the definition of the operator== to get the compiler to warn me with another "statement has no effect" for the line "b == 1" ?

like image 452
Dave Lawrence Avatar asked May 01 '18 13:05

Dave Lawrence


1 Answers

In C++17, you can mark the operator overload as [[nodiscard]]:

[[nodiscard]] bool operator==(int _value) const { return value == _value; }

This will encourage the compiler to produce a warning if the return value is unused.

live example on wandbox.org


From cppreference:

[[nodiscard]]

Appears in a function declaration, enumeration declaration, or class declaration. If a function declared nodiscard or a function returning an enumeration or class declared nodiscard by value is called from a discarded-value expression other than a cast to void, the compiler is encouraged to issue a warning.

like image 124
Vittorio Romeo Avatar answered Oct 14 '22 00:10

Vittorio Romeo