在 if 语句中沉默 -wunused-变量



以下代码生成一个警告,指出未使用temp(这是真的):

#include <cstdio>
int f() { return 5; }
int main() {
    if(const int& temp = f()) {
        printf("hello!n");
    }
    return 0;
}

问题是我需要这样做而不会使用 gcc -Wall 和 clang -Weverything 生成警告(我正在实现类似于 Catch SECTION()内容的功能)。

那么有什么方法可以让它沉默吗?我尝试使用__attribute__((unused)).

全局使用 -Wno-unused-variable 对我来说不是一个选择,因为我正在编写一个仅标题库。

#include <cstdio>
int f() { return 5; }
int main()
{
  if (const int &temp __attribute__((unused)) = f()) {
    printf("hello!n");
  }
  return 0;
}

这消除了对 GCC 和叮当声的警告。

如果未使用temp,本质上也可能不需要它。删除它。

#include <cstdio>
int f() { return 5; }
int main() {
    if(f()) {
        printf("hello!n");
    }
    return 0;
}

我意识到这是一个MCVE,那么为什么它首先需要在那里呢?

正如您在注释中提到的,temp的析构函数在目标代码中很重要。添加一组额外的大括号将增加对临时生存期的控制并确保其使用(因此删除警告);

#include <iostream>
using namespace std;
struct A {
    ~A() { cout << "~A()" << endl; }
    explicit operator bool() const { return true; }
};
A f() { return A{}; }
int main() {
    { // braced to limit scope...
        auto&& a = f(); // can be const A&
        if ( a ) {
            cout << "hello!" << endl;
        }
    } // braced to limit scope....
    return 0;
}

演示代码。

鉴于temp生命周期的额外约束已延长到相关else的末尾,只需强制将警告静音即可(编译器受限)。

if (const int &temp __attribute__((unused)) = f())

C++11 带来了属性的[[...]]样式,但unused不是标准的,但 clang 确实支持这种语法[[gnu::unused]]

在跳过箍试图在不使用__attribute__((unused))的情况下解决这个问题(这完全是正确的解决方案)之后,我决定解决这个问题。

if(const int& temp = ((true) ? f() : (static_cast<void>(temp), f())) )

true周围的括号禁止显示死代码警告,条件运算符在分配temp之前禁止显示有关使用 的警告,强制转换为 void 删除未使用的变量警告。

GCC的-Wall和Clang的-Weverything无话可说,尽管一个理性的人可能会。

公平警告:如果temp曾经使用 volatile 复制构造函数声明volatile,这将是 UB(关于何时发生左值到右值转换的一些晦涩规则)。

最新更新