在下面的例子中:
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;
}
编译给出以下内容:
$ 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;
^
这很好,因为它警告我输入错误并错误输入 == for =
但是我的Test类也是如此。我如何标记类或 operator== 的定义以使编译器用另一个“语句无效”警告我“b == 1”行?
最佳答案
在 C++17 中,您可以将运算符重载标记为 [[nodiscard]]
:
[[nodiscard]] bool operator==(int _value) const { return value == _value; }
如果返回值未被使用,这将鼓励编译器产生警告。
来自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.
关于c++ - 如何在过载时强制发出 "statement has no effect"警告==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50117312/