How to avoid warning when using scope guard?

守給你的承諾、 提交于 2019-12-10 15:39:50

问题


I am using folly scope guard, it is working, but it generates a warning saying that the variable is unused:

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

The code:

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

How to avoid such warning?


回答1:


You can disable this warnings by -Wno-unused-variable, though this is a bit dangerous (you loose all realy unused variables).

One possible solution is to actually use the variable, but do nothing with it. For example, case it to void:

(void) g;

which can be made into a macro:

#define IGNORE_UNUSED(x) (void) x;

Alternatively, you can use the boost aproach: declare a templated function that does nothing and use it

template <typename T>
void ignore_unused (T const &) { }

...

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



回答2:


You can just label the variable as being unused:

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

Or cast it to void:

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

Neither is great, imo, but at least this lets you keep the warnings.



来源:https://stackoverflow.com/questions/35587076/how-to-avoid-warning-when-using-scope-guard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!