使用nullptr_t时,为什么会出现"参数设置但未使用"警告?

Ven*_*emo 11 c++ warnings g++ nullptr c++11

我有一个自定义类实现operator==nullptr.

这是我的代码愚蠢到一个简单的例子:

#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;
}
Run Code Online (Sandbox Code Playgroud)

代码按预期工作,但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 {
                                    ^
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

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

was*_*ful 9

不是真的,为什么出现这种情况的答案,但无论如何,能有什么价值n,但nullptr

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

bool operator==(std::nullptr_t) const {
    return this->v == nullptr;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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

bool operator==(const std::nullptr_t& n) const {
    return this->v == n;
}
Run Code Online (Sandbox Code Playgroud)

EDIT2:

有关未使用变量警告的更多方法可以在这个问题中找到(thx @ShafikYaghmour将其指向评论中).上面的例子涵盖了"隐含"的方式.

可以使用显式解决方案,但由于有效地使用了参数,因此IMHO看起来不那么连贯.测试显式解决方案包括:

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;
}
Run Code Online (Sandbox Code Playgroud)

GCC的非便携式解决方案:

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

  • 我实际上相信这个*是一个答案,因为它提供了一种非常合理的方法来避免警告.使用`std :: nullptr_t`类型的对象的标识符是毫无意义的. (7认同)
  • 如果它不是答案,那么IMO应该是评论. (3认同)
  • 但是,这种情况可能发生在模板中,其中`std :: nullptr_t`实际上是一个类型参数. (3认同)