Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a "parameter set but not used" warning when using nullptr_t?

I have a custom class implementing operator== with nullptr.

Here is my code dumbed down into a simple example:

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

The code works as expected but g++ (version 6.2.1) gives me the following warning:

[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 {
                                    ^

What am I doing wrong?

NOTE: I'm using -Wall -Wextra.

like image 493
Venemo Avatar asked Nov 24 '16 15:11

Venemo


1 Answers

Not really an answer on why this happens, but anyway what value could have n but nullptr?

Returning this->v == nullptr and making the argument unnamed removes the warning:

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

EDIT:

Declaring n as an rvalue reference, or as a const lvalue reference also removes the warning:

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

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

EDIT2:

More ways to silence a warning about unused variables can be found in this question (thx @ShafikYaghmour for pointing it in the comments). The examples above cover the "implicit" ways.

Explicit solutions are available, but IMHO look less coherent since the parameter is effectively used. Tested explicit solutions include:

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

Non portable solution for GCC:

bool operator==(__attribute__((unused)) std::nullptr_t n) const {
    return this->v == n;
}
like image 125
rgmt Avatar answered Nov 06 '22 18:11

rgmt