使用范围防护时如何避免警告

How to avoid warning when using scope guard?

本文关键字:何避免 警告 使用范围      更新时间:2023-10-16

我正在使用愚蠢的作用域保护,它正在工作,但它生成一个警告,指出该变量未使用:

warning: unused variable ‘g’ [-Wunused-variable]

代码:

folly::ScopeGuard g = folly::makeGuard([&] {close(sock);});

如何避免此类警告?

您可以将变量标记为未使用:

folly::ScopeGuard g [[gnu::unused]] = folly::makeGuard([&] {close(sock);});

或者将其转换为无效:

folly::ScopeGuard g = folly::makeGuard([&] {close(sock);});
(void)g;

两者都不是很好,imo,但至少这可以让你保持警告。

您可以通过

-Wno-unused-variable禁用此警告,尽管这有点危险(您丢失了所有实际未使用的变量)。

一种可能的解决方案是实际使用该变量,但不对它执行任何操作。例如,将其作废:

(void) g;

可以制作成宏:

#define IGNORE_UNUSED(x) (void) x;

或者,您可以使用 boost aproach:声明一个不执行任何操作的模板化函数并使用它

template <typename T>
void ignore_unused (T const &) { }
...
folly::ScopeGuard g = folly::makeGuard([&] {close(sock);});
ignore_unused(g);