使用护目镜时如何避免警告?

时间:2016-02-23 20:02:36

标签: c++ c++11 scopeguard folly

我正在使用愚蠢的范围保护,它正在工作,但它会生成一个警告,说该变量未使用:

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

代码:

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

如何避免这种警告?

2 个答案:

答案 0 :(得分:5)

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

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

或将其转为无效:

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

既不是伟大的,也不是,但至少这可以让你保持警告。

答案 1 :(得分:4)

您可以-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);
相关问题