C++ 如何最好地消除有关未使用变量的警告?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1486904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I best silence a warning about unused variables?
提问by Phil Hannent
I have a cross platform application and in a few of my functions not all the values passed to functions are utilised. Hence I get a warning from GCC telling me that there are unused variables.
我有一个跨平台的应用程序,在我的一些函数中,并非所有传递给函数的值都被利用。因此,我收到 GCC 的警告,告诉我有未使用的变量。
What would be the best way of coding around the warning?
围绕警告进行编码的最佳方式是什么?
An #ifdef around the function?
函数周围的#ifdef?
#ifdef _MSC_VER
void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal qrLeft, qreal qrTop, qreal qrWidth, qreal qrHeight)
#else
void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal /*qrLeft*/, qreal /*qrTop*/, qreal /*qrWidth*/, qreal /*qrHeight*/)
#endif
{
This is so ugly but seems like the way the compiler would prefer.
这太丑了,但似乎是编译器喜欢的方式。
Or do I assign zero to the variable at the end of the function? (which I hate because it's altering something in the program flow to silence a compiler warning).
或者我是否在函数末尾为变量赋值为零?(我讨厌它,因为它改变了程序流中的某些内容以消除编译器警告)。
Is there a correct way?
有正确的方法吗?
回答by Alex B
You can put it in "(void)var;
" expression(does nothing) so that a compiler sees it is used. This is portable between compilers.
你可以把它放在 " (void)var;
" 表达式中(什么都不做),以便编译器看到它被使用。这在编译器之间是可移植的。
E.g.
例如
void foo(int param1, int param2)
{
(void)param2;
bar(param1);
}
Or,
或者,
#define UNUSED(expr) do { (void)(expr); } while (0)
...
void foo(int param1, int param2)
{
UNUSED(param2);
bar(param1);
}
回答by ezpz
In GCC and Clang you can use the __attribute__((unused))
preprocessor directive to achieve your goal.
For example:
在 GCC 和 Clang 中,您可以使用__attribute__((unused))
预处理器指令来实现您的目标。
例如:
int foo (__attribute__((unused)) int bar) {
return 0;
}
回答by scx
C++17 now provides the [[maybe_unused]]
attribute.
C++17 现在提供了该[[maybe_unused]]
属性。
http://en.cppreference.com/w/cpp/language/attributes
http://en.cppreference.com/w/cpp/language/attributes
Quite nice and standard.
相当不错和标准。
回答by alex tingle
Your current solution is best - comment out the parameter name if you don't use it. That applies to all compilers, so you don't have to use the pre-processor to do it specially for GCC.
您当前的解决方案是最好的 - 如果您不使用参数名称,请将其注释掉。这适用于所有编译器,因此您不必使用预处理器专门为 GCC 执行此操作。
回答by Shafik Yaghmour
C++17 Update
C++17 更新
In C++17 we gain the attribute [[maybe_unused]]which is covered in [dcl.attr.unused]
在 C++17 中,我们获得了[[maybe_unused]]属性,该属性包含在[dcl.attr.unused] 中
The attribute-token maybe_unused indicates that a name or entity is possibly intentionally unused. It shall appear at most once in each attribute-list and no attribute-argument-clause shall be present. ...
Example:
[[maybe_unused]] void f([[maybe_unused]] bool thing1, [[maybe_unused]] bool thing2) { [[maybe_unused]] bool b = thing1 && thing2; assert(b); }
Implementations should not warn that b is unused, whether or not NDEBUG is defined. —end example ]
属性标记maybe_unused 表示名称或实体可能是有意未使用的。它在每个属性列表中最多出现一次,并且不应出现属性参数子句。...
例子:
[[maybe_unused]] void f([[maybe_unused]] bool thing1, [[maybe_unused]] bool thing2) { [[maybe_unused]] bool b = thing1 && thing2; assert(b); }
无论是否定义了 NDEBUG,实现都不应该警告 b 未使用。—结束示例]
For the following example:
对于以下示例:
int foo ( int bar) {
bool unused_bool ;
return 0;
}
Both clang and gcc generate a diagnostic using -Wall -Wextrafor both barand unused_bool(See it live).
clang 和 gcc 都使用-Wall -Wextra为bar和未使用的_bool生成诊断信息(实时查看)。
While adding [[maybe_unused]]silences the diagnostics:
添加[[maybe_unused]]会使诊断静音:
int foo ([[maybe_unused]] int bar) {
[[maybe_unused]] bool unused_bool ;
return 0;
}
看直播。
Before C++17
在 C++17 之前
In C++11 an alternative form of the UNUSED
macro could be formed using a lambda expression(via Ben Deane) with an capture of the unused variable:
在 C++11 中,UNUSED
可以使用 lambda 表达式(通过 Ben Deane)捕获未使用的变量来形成宏的另一种形式:
#define UNUSED(x) [&x]{}()
The immediate invocation of the lambda expression should be optimized away, given the following example:
给定以下示例,应优化 lambda 表达式的立即调用:
int foo (int bar) {
UNUSED(bar) ;
return 0;
}
we can see in godboltthat the call is optimized away:
我们可以在Godbolt中看到调用被优化掉了:
foo(int):
xorl %eax, %eax
ret
回答by Marcin Wyszynski
An even cleaner way is to just comment out variable names:
更简洁的方法是注释掉变量名:
int main(int /* argc */, char const** /* argv */) {
return 0;
}
回答by Marcin Wyszynski
A coworker just pointed me to this nice little macro here
一个同事刚刚向我指出这个可爱的小宏在这里
For ease I'll include the macro below.
为方便起见,我将在下面包含宏。
#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*@unused@*/ x
#else
# define UNUSED(x) x
#endif
void dcc_mon_siginfo_handler(int UNUSED(whatsig))
回答by Digital Trauma
gccdoesn't flag these warnings by default. This warning must have been turned on either explicitly by passing -Wunused-parameter
to the compiler or implicitly by passing -Wall -Wextra
(or possibly some other combination of flags).
默认情况下,gcc不会标记这些警告。此警告必须已通过传递-Wunused-parameter
给编译器显式打开或通过传递-Wall -Wextra
(或可能是其他标志组合)隐式打开。
Unused parameter warnings can simply be suppressed by passing -Wno-unused-parameter
to the compiler, but note that this disabling flag must come after any possible enabling flags for this warning in the compiler command line, so that it can take effect.
可以简单地通过传递-Wno-unused-parameter
给编译器来抑制未使用的参数警告,但请注意,此禁用标志必须位于编译器命令行中此警告的任何可能启用标志之后,以便它可以生效。
回答by Philippe
macro-less and portable way to declare one or moreparameters as unused:
将一个或多个参数声明为未使用的无宏且可移植的方法:
template <typename... Args> inline void unused(Args&&...) {}
int main(int argc, char* argv[])
{
unused(argc, argv);
return 0;
}
回答by Ben Dadsetan
Using preprocessor directives is considered evil most of the time. Ideally you want to avoid them like the Pest. Remember that making the compiler understand your code is easy, allowing other programmers to understand your code is much harder. A few dozen cases like this here and there makes it very hard to read for yourself later or for others right now.
大多数情况下,使用预处理器指令被认为是邪恶的。理想情况下,您希望像 Pest 一样避开它们。请记住,让编译器理解你的代码很容易,让其他程序员理解你的代码要困难得多。在这里和那里有几十个这样的案例,让自己或现在的其他人都很难阅读。
One way might be to put your parameters together into some sort of argument class. You could then use only a subset of the variables (equivalent to your assigning 0 really) or having different specializations of that argument class for each platform. This might however not be worth it, you need to analyze whether it would fit.
一种方法可能是将您的参数放在某种参数类中。然后,您可以仅使用变量的一个子集(实际上相当于您分配 0)或为每个平台使用该参数类的不同专业化。然而,这可能不值得,您需要分析它是否适合。
If you can read impossible templates, you might find advanced tips in the "Exceptional C++" book. If the people who would read your code could get their skillset to encompass the crazy stuff taught in that book, then you would have beautiful code which can also be easily read. The compiler would also be well aware of what you are doing (instead of hiding everything by preprocessing)
如果您能阅读不可能的模板,您可能会在“Exceptional C++”一书中找到高级技巧。如果阅读你的代码的人能够获得他们的技能来囊括那本书中教授的疯狂内容,那么你就会拥有漂亮的代码,也可以很容易地阅读。编译器也很清楚你在做什么(而不是通过预处理隐藏所有内容)