在C++中禁止使用未使用的变量警告=>编译器错误或代码错误?

Wil*_*mKF 11 c++ templates language-lawyer member-variables

目前,我使用以下函数模板来抑制未使用的变量警告:

template<typename T>
void
unused(T const &) {
  /* Do nothing. */
}
Run Code Online (Sandbox Code Playgroud)

但是,当从Linux移植到cygwin时,我现在在g ++ 3.4.4上遇到编译器错误(在linux上我是3.4.6,所以这可能是一个bug修复?):

Write.cpp: In member function `void* Write::initReadWrite()':
Write.cpp:516: error: invalid initialization of reference of type 'const volatile bool&' from expression of type 'volatile bool'
../../src/common/Assert.h:27: error: in passing argument 1 of `void unused(const T&) [with T = volatile bool]'
make[1]: *** [ARCH.cygwin/release/Write.o] Error 1
Run Code Online (Sandbox Code Playgroud)

未使用的参数是一个声明为的成员变量:

  volatile bool readWriteActivated;
Run Code Online (Sandbox Code Playgroud)

这是编译器错误还是我的代码中的错误?

这是最小的测试用例:

template<typename T>
void unused(T const &) { }

int main() {
  volatile bool x = false;
  unused(!x); // type of "!x" is bool
}
Run Code Online (Sandbox Code Playgroud)

haa*_*vee 28

指示您实际上不使用参数的实际方法是不给它命名:

int f(int a, float) {
     return a*2;
}
Run Code Online (Sandbox Code Playgroud)

将打开所有警告的所有地方编译,而不会警告未使用的浮动.即使参数确实在原型中有一个名称(例如int f(int a, float f);),它仍然不会抱怨.

  • 是的,我通常使用int f(int count,float/*epsilon*/)之类的东西来命名未使用的参数及其含义. (7认同)
  • 这不是问题所在.省略函数arg的变量名称效果很好,但这里变量是在函数内部声明的,因此不能省略.此外,在这种情况下,需要变量名称,因为它在一些#ifdef情况下使用,而未使用的是在其他情况下,因此不会生成警告. (4认同)

Tom*_*Tom 9

我不是100%确定这是可移植的,但这是我通常用来抑制有关未使用变量的警告的习惯用法.这里的背景是一个信号处理程序,只用来捕捉SIGINTSIGTERM,所以如果函数永远叫我知道它的时候,程序退出.

volatile bool app_killed = false;
int signal_handler(int signum)
{
    (void)signum; // this suppresses the warnings
    app_killed = true;
}
Run Code Online (Sandbox Code Playgroud)

我倾向于不喜欢混乱参数列表__attribute__((unused)),因为无需借助于Visual C++的宏就可以使用转换为无效的技巧.


Wil*_*mKF 4

这是一个编译器错误,没有已知的解决方法:

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=42655

在 v4.4 中已修复。