4

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?

Alex
  • 3,301
  • 4
  • 29
  • 43
  • 1
    I think you are not supposed to use `folly::ScopeGuard g = folly::makeGuard([&] {close(sock);});`. You are supposed to use `SCOPE_EXIT{close(sock);}`. See if that makes the warning go away. If it doesn't, there is probably a way to hack a use into the definition. – nwp Feb 23 '16 at 20:22
  • 2
    What compiler version? If `g`'s destructor actually does something then the compiler should not be warning about this , it could be considered a bug (and may have been fixed in later versions). – M.M Feb 23 '16 at 20:26
  • 1
    It should be noted that C++17 seems to be getting a `[[maybe_unused]]` attribute that would provide a standard-guaranteed way of declaring that a variable will be unusued. – Nicol Bolas Feb 23 '16 at 20:26
  • 1
    @M.M: It is not unreasonable for compilers to warn about such variables, even if they have destructors that do things. If you just declare a `std::string` and accidentally forget to use it, the compiler still ought to warn about it, since you almost certainly meant to do something with it. – Nicol Bolas Feb 23 '16 at 20:27
  • @NicolBolas fair point – M.M Feb 23 '16 at 20:43
  • @M.M, I am using gcc 5.1.1 – Alex Feb 24 '16 at 02:36

2 Answers2

5

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.

Barry
  • 286,269
  • 29
  • 621
  • 977
4

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);
lisyarus
  • 15,025
  • 3
  • 43
  • 68