在 if 语句中沉默 -wunused-变量
Silencing -Wunused-variable in an if statement
以下代码生成一个警告,指出未使用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(关于何时发生左值到右值转换的一些晦涩规则)。
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- 警告:未使用的变量“arrPixel”[-Wunused-variable]
- 在 if 语句中沉默 -wunused-变量
- 未使用的变量 'class' [-Wunused-变量] - 错误/警告