Clang 8.0.0 and GCC 9.1.0 seem to disagree as to whether this is valid code.
struct Foo {
Foo([[maybe_unused]] int x) {}
};
int main() {}
Clang produces no warnings (even with -Wall -Wextra -Wpedantic
) but GCC produces this error:
test.cpp:2:7: error: expected unqualified-id before '[' token
2 | Foo([[maybe_unused]] int x) {}
| ^
test.cpp:2:7: error: expected ')' before '[' token
2 | Foo([[maybe_unused]] int x) {}
| ~^
| )
So which compiler has a bug?
The constructor attribute causes the function to be called automatically before execution enters main () . Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called.
Attribute vs ParameterAn attribute is a variable of any type that is declared directly in a class. A parameter is a variable defined by the function that receives a value when it is called. An attribute is used with classes and objects. A parameter is used with a function or a method.
Attributes are metadata extensions that give additional information to the compiler about the elements in the program code at runtime.
A custom attribute is an additional property that you can define to help describe business glossary assets. Labels are keywords that you can define to help describe any type of asset in the metadata repository. Users can use both custom attributes and labels to refine a search in the business glossary.
Yes, they can be applied. The standard allows this.
10.6.6 Maybe unused attribute [dcl.attr.unused]
...
2 The attribute may be applied to the declaration of a class, a typedef-name, a variable, a non-static data member, a function, an enumeration, or an enumerator.
So Clang is correct here and this is a GCC bug. A bug report has already been filed for this titled: maybe_unused attribute triggers syntax error when used on first argument to a constructor
Your code is valid
The
[[maybe_unused]]
attribute can be applied to the declaration of a struct, enum, union, typedef, variable (including member variables), function, or enumerator. Implementations are encouraged to not emit a diagnostic when such an entity is unused or when the entity is used despite being marked as[[maybe_unused]]
.
However there is already a bug report for this in gcc
maybe_unused attribute triggers syntax error when used on first argument to a constructor . gcc
probably is not able to parse it correctly.
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