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.
不是真的,为什么出现这种情况的答案,但无论如何,能有什么价值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)
| 归档时间: |
|
| 查看次数: |
2299 次 |
| 最近记录: |