警告 C4101 未引用的局部变量
Warning C4101 unreferenced local variable
void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
.....lots of code here not using param
}
编译出错,即使在代码中我也不想发出警告。
自 C++17 以来,我们有了maybe_unused
属性来抑制对未使用实体的警告:
void func([[maybe_unused]] char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}
很简单。如果未定义_XYZ_
则函数中不使用变量param
,并且编译器会发出可以转换为的衰减:
译自编译者:
我的朋友,你问我要一段名叫
param
的记忆,但你是 不使用它。你确定这是故意的吗?
在 C++17 的[[maybe_unused]]
属性之前,可以使用特定于编译器的命令。
在 MSVC 中,您可以执行以下操作:
#pragma warning(push)
#pragma warning(disable:4101)
void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}
#pragma warning(pop)
在Borland/Embarcadero,你可以这样做:
#pragma argsused
void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}
在 GCC 中,您可以使用以下方法之一:
void func(__attribute__((unused)) char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}
void func(__unused char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}
void func([[gnu::unused]] char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}
或者,您可以简单地引用参数,而不使用任何特定于编译器的技巧:
void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#else
(void)param;
#endif
}
怎么样:static_cast<void>(param);
使用同样用于丢弃标记为[[nodiscard]]
的结果的相同方法:
除了强制转换到无效之外,鼓励编译器发出 警告。
[[nodiscard]] bool is_good_idea();
void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#else
// suppress warning:
static_cast<void>(param);
#endif
// also valid:
static_cast<void>(is_good_idea());
}
编译器不会生成任何其他指令:)
相关文章:
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- 返回对局部变量 - C++ 的引用
- 警告 C4101 未引用的局部变量
- 现代编译器会优化只引用对象子集的局部变量吗
- 右值引用和局部变量的移动
- 结构数组 - 未引用的局部变量
- 返回对局部变量的引用是否正常工作?
- 为什么 ++ 运算符触发器返回对局部变量警告的引用
- 三元运算符:编译器不发出局部变量警告的返回引用
- 为什么 C++ 编译器不警告返回对局部变量的引用
- 变量循环范围会导致返回局部变量的地址引用
- 通过引用返回局部变量
- 为什么我得到未引用的局部变量
- 返回由引用指定的引用局部变量
- 返回静态局部变量作为引用
- 没有返回对局部变量的引用的编译器警告
- 为什么在这段代码中返回对局部变量的引用
- 引用与设置局部变量
- 通过引用参数将局部变量分配给
- 捕获和调试对移动lambda内部局部变量引用的无效使用