我有一个自定义类实现了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;
}
代码按预期工作,但是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
。
#include <iostream> int main() { std::nullptr_t n = nullptr; if (n == nullptr) std::cout << "yes"; }
- Christian Hackln=n;
可以消除警告。看起来编译器知道n
可能为NULL
,并简单地优化了对它的引用,最终产生了警告。 - Sam Varshavchiknullptr_t
对象进行 lvalue-to-rvalue 转换不会访问其存储的值。但还是应该提交一个 bug 报告。 - T.C.