【发布时间】:2016-11-24 15:38:13
【问题描述】:
我有一个自定义类实现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。
【问题讨论】:
-
@SamVarshavchik 尝试 -Wall -Wextra。可在 wandbox 的 6.1 上重现:melpon.org/wandbox/permlink/OGeniUkFzE8dRP1v
-
有趣。请注意,您可以进一步简化它:
#include <iostream> int main() { std::nullptr_t n = nullptr; if (n == nullptr) std::cout << "yes"; } -
@wasthishelpful:也许 GCC 在此处生成警告时证明是正确的,但措辞 “参数集但未使用” 肯定还有很多不足之处。跨度>
-
将
n=n;添加到函数中会使警告消失。看起来编译器知道n可以是NULL,并简单地优化对它的引用,然后最终产生警告。 -
nullptr_t对象上的左值到右值转换不会访问其存储的值。无论如何都应该提交一个错误。
标签: c++ c++11 g++ warnings nullptr