[英]Why am I getting a “parameter set but not used” warning when using nullptr_t?
我有一個自定義類實現operator==
with 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;
}
代碼按預期工作,但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
聲明為右值引用或作為const左值引用也會刪除警告:
bool operator==(std::nullptr_t&& n) const {
return this->v == n;
}
bool operator==(const std::nullptr_t& n) const {
return this->v == n;
}
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;
}
GCC的非便攜式解決方案:
bool operator==(__attribute__((unused)) std::nullptr_t n) const {
return this->v == n;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.