ink*_*boo 75 c++ c++11 unused-variables
在c ++ 03及更早版本中禁用有关未使用参数的编译器警告我通常使用这样的代码:
#define UNUSED(expr) do { (void)(expr); } while (0)
Run Code Online (Sandbox Code Playgroud)
例如
int main(int argc, char *argv[])
{
UNUSED(argc);
UNUSED(argv);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但宏不是c ++的最佳实践,所以.c ++ 11标准是否有更好的解决方案?我的意思是我可以摆脱宏吗?
谢谢大家!
Hen*_*rik 187
您可以省略参数名称:
int main(int, char *[])
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在main的情况下,您甚至可以完全省略参数:
int main()
{
// no return implies return 0;
}
Run Code Online (Sandbox Code Playgroud)
请参阅C++ 11标准中的"第3.6节"启动和终止".
Ori*_*ent 44
还有就是<tuple>在C++ 11,其中包括准备使用std::ignore的对象,这让我们写(很可能不附加任何运行时开销):
void f(int x)
{
std::ignore = x;
}
Run Code Online (Sandbox Code Playgroud)
Mad*_*ist 38
为此,我使用了一个带有空体的函数:
template <typename T>
void ignore(T &&)
{ }
void f(int a, int b)
{
ignore(a);
ignore(b);
return;
}
Run Code Online (Sandbox Code Playgroud)
我希望任何认真的编译器能够优化函数调用,它会为我静音警告.
Lig*_*ica 30
什么都没有,没有.
所以你坚持使用相同的旧选项.您是否乐于完全省略参数列表中的名称?
int main(int, char**)
Run Code Online (Sandbox Code Playgroud)
main当然,在特定情况下,您可以简单地省略参数本身:
int main()
Run Code Online (Sandbox Code Playgroud)
还有典型的特定于实现的技巧,例如GCC __attribute__((unused)).
Nik*_*kko 28
要"禁用"此警告,最好是避免编写参数,只需编写类型即可.
void function( int, int )
{
}
Run Code Online (Sandbox Code Playgroud)
或者如果您愿意,请将其评论出来:
void function( int /*a*/, int /*b*/ )
{
}
Run Code Online (Sandbox Code Playgroud)
您可以混合命名和未命名的参数:
void function( int a, int /*b*/ )
{
}
Run Code Online (Sandbox Code Playgroud)
使用C++ 17,你有[[maybe_unused]]属性说明符,如:
void function( [[maybe_unused]] int a, [[maybe_unused]] int b )
{
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*son 14
宏可能不是理想的,但它们为这个特定的目的做得很好.我会说坚持使用宏.
jca*_*zac 13
你对旧的和标准的方式有什么看法?
void f(int a, int b)
{
(void)a;
(void)b;
return;
}
Run Code Online (Sandbox Code Playgroud)
Rei*_*ica 12
没有什么新的可用.
对我来说最有效的是在实现中注释掉参数名称.这样,您就可以摆脱警告,但仍保留一些参数的概念(因为名称可用).
你的宏(以及其他所有的逐行转换方法)都有缺点,你可以在使用宏之后实际使用该参数.这可能使代码难以维护.
man*_*lio 12
<boost/core/ignore_unused.hpp>为此,Boost标头(Boost> = 1.56)定义了函数模板boost::ignore_unused().
int fun(int foo, int bar)
{
boost::ignore_unused(bar);
#ifdef ENABLE_DEBUG_OUTPUT
if (foo < bar)
std::cerr << "warning! foo < bar";
#endif
return foo + 2;
}
Run Code Online (Sandbox Code Playgroud)
PS C++ 17具有[[maybe_unused]]抑制未使用实体警告的属性.