c++ - 为什么我在使用 nullptr_t 时收到 "parameter set but not used"警告?

标签 c++ c++11 g++ warnings nullptr

我有一个使用 nullptr 实现 operator== 的自定义类。

这是我的代码简化成一个简单的例子:

#include <cstdint>
#include <iostream>

class C {
private:
    void *v = nullptr;

public:
    explicit C(void *ptr) : v(ptr) { }

    bool operator==(std::nullptr_t n) const {
        return this->v == n;
    }
};

int main()
{
    uint32_t x = 0;
    C c(&x);
    std::cout << (c == nullptr ? "yes" : "no") << std::endl;

    C c2(nullptr);
    std::cout << (c2 == nullptr ? "yes" : "no") << std::endl;


    return 0;
}

代码按预期工作,但 g++(版本 6.2.1)给我以下警告:

[Timur@Timur-Zenbook misc]$ g++ aaa.cpp -o aaa -Wall -Wextra
aaa.cpp: In member function ‘bool C::operator==(std::nullptr_t) const’:
aaa.cpp:12:36: warning: parameter ‘n’ set but not used [-Wunused-but-set-parameter]
     bool operator==(std::nullptr_t n) const {
                                    ^

我做错了什么?

注意:我正在使用 -Wall -Wextra

最佳答案

对于为什么会发生这种情况并没有真正的答案,但无论如何什么值可以有 n 而不是 nullptr

返回 this->v == nullptr 并使参数未命名会删除警告:

bool operator==(std::nullptr_t) const {
    return this->v == nullptr;
}

编辑:

n 声明为右值引用或常量左值引用也会删除警告:

bool operator==(std::nullptr_t&& n) const {
    return this->v == n;
}

bool operator==(const std::nullptr_t& n) const {
    return this->v == n;
}

编辑 2:

可以在 this question 中找到更多消除未使用变量警告的方法。 (感谢@ShafikYaghmour 在评论中指出它)。上面的示例涵盖了“隐式”方式。

明确的解决方案是可用的,但恕我直言,由于有效地使用了参数,因此看起来不太连贯。经过测试的显式解决方案包括:

bool operator==(std::nullptr_t n) const {
    (void)n;
    return this->v == n;
}

#define UNUSED(expr) do { (void)(expr); } while (0)

bool operator==(std::nullptr_t n) const {
    UNUSED(n);
    return this->v == n;
}

GCC 的非可移植解决方案:

bool operator==(__attribute__((unused)) std::nullptr_t n) const {
    return this->v == n;
}

关于c++ - 为什么我在使用 nullptr_t 时收到 "parameter set but not used"警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40790212/

相关文章:

c++ - 使用 native 依赖项加载 clr 库

C++ 如何在 C++ 中使用 dlopen()?

c++ - thread::join 上是否存在具有同步关系的隐式内存屏障?

linux - 如何将/var/log/messages 中的段错误指令指针地址映射到 .map 文件中的地址/函数?

linux - Linux g++ 中 MSVC++ _wrename 的等价物?

c++ - OpenCV imshow 不在 osx 中显示图像

c++ - 如何用通用 TR1 函数对象包装多个函数重载?

c++ - 了解左值和右值但不确定此代码为何有效

c++ - 从 std 命名空间专门化函数模板的想法有多糟糕?

c++ - 如何修复 'undefined reference' 错误 opencv 和 g++