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" ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With