C++17 introduces the attribute [[maybe_unused]].
I assume this a standardized version of GCC and Clang's: __attribute__((unused)).
For unused functions that I don't want to see a warning from,
should I be specifying the attribute on
function declarations?
void maybe_used_function() [[maybe_unused]];
or function definitions?
void maybe_used_function() [[maybe_unused]] {
/* impl */
}
Either one? Both?
Will the effect be the same on both the standardized and compiler specific attributes?
I can't find any clear documentation on placement behaviour, and what the common practice is.
When I place the attribute before the function body in a definition, GCC and clang give an error:
void function();
int main(){}
void function() __attribute__((unused)) {}
warning: GCC does not allow 'unused' attribute in this position on a function definition [-Wgcc-compat] void function() __attribute__((unused)) {
However, the attribute can be placed in two other places without error:
__attribute__((unused)) void __attribute__((unused)) function() {}
Maybe one of these ways is how I'm expected to use the attribute on function definitions?
The [[nodiscard]] attribute can be used to indicate that the return value of a function shouldn't be ignored when you do a function call. If the return value is ignored, the compiler should give a warning on this.
The __attribute__ directive is used to decorate a code declaration in C, C++ and Objective-C programming languages. This gives the declared code additional attributes that would help the compiler incorporate optimizations or elicit useful warnings to the consumer of that code.
Neither. In
[[attr1]] void [[attr2]] f [[attr3]] () [[attr4]] {}
attr1
and attr3
appertain (or apply) to f
itself.attr2
appertains to the preceding type, void
.attr4
appertains to f
's type ("function of ()
returning void
), not f
.You want maybe_unused
to appertain to f
, so you can put it in position 1 or 3, but not 2 or 4.
@ildjarn's answer covers the rest.
For GCC's __attribute__
, you'll have to check its documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With