使用[[maybe_unused]]有什么好处?考虑一下
int winmain(int instance, int /*prevInstance*/, const char */*cmdline*/, int show);
int winmain(int instance, [[maybe_unused]] int prevInstance, [[maybe_unused]] const char *cmdline, int show);有些人可能会坚持使用注释是丑陋的,因为这个关键字是在这些情况下创建并打算使用的,我完全同意这一点,但maybe_unused关键字对我来说似乎有点太长了,使得代码稍微难以阅读。
我想尽可能“严格”地遵循这个标准,但它值得使用吗?
发布于 2018-03-16 20:32:56
如果参数肯定没有使用,[[maybe_unused]]就不是特别有用,未命名的参数和注释对此很好。
[[maybe_unused]]主要用于可能未使用的内容,如在
void fun(int i, int j) {
assert(i < j);
// j not used here anymore
}这不能用未命名的参数来处理,但是如果定义了NDEBUG,将会产生一个警告,因为j未使用。
当参数仅用于(可能禁用)日志记录时,可能会出现类似的情况。
发布于 2018-03-16 21:00:53
Baum mit Augen's answer是权威性的和无可争辩的解释。我只想给出另一个例子,它不需要宏。具体来说,C++17引入了constexpr if结构。所以你可能会看到这样的模板代码(除了愚蠢的功能):
#include <type_traits>
template<typename T>
auto add_or_double(T t1, T t2) noexcept {
if constexpr (std::is_same_v<T, int>)
return t1 + t2;
else
return t1 * 2.0;
}
int main(){
add_or_double(1, 2);
add_or_double(1.0, 2.0);
}在写这篇文章时,GCC 8.0.1警告我,当else分支是实例化的分支时,t2是未使用的。在这种情况下,该属性也是必不可少的。
https://stackoverflow.com/questions/49320810
复制相似问题