c++ - 如何在过载时强制发出 "statement has no effect"警告==

标签 c++ operator-overloading

在下面的例子中:

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

如果返回值未被使用,这将鼓励编译器产生警告。

live example on wandbox.org


来自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/

相关文章:

c++ - 为什么cout << "hello"选择operator<<的非成员版本?

c++ - 从 new 重载调用构造函数和直接调用构造函数有什么区别?

c++ - C++ 中的 shared_ptr 和引用

c++ - 输入一个指针并返回该指针的方法?

C++ - 为学校构建我自己的 String 类,无法正确重载 < 运算符

c++ - 将 alpha channel 添加到 opencv Mat

c++ - 将强制转换运算符重载到 std::map 的正确语法是什么?

c++ - 如何使用 lambda 在 std::function 参数中推导模板类型?

c++ - 如何访问 boost 子图 'graph' 属性?

c++ - 未初始化和不确定之间的区别