Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can attributes be applied to constructor parameters?

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?

like image 841
Indiana Kernick Avatar asked May 21 '19 04:05

Indiana Kernick


People also ask

What is attribute in constructor?

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.

Are attributes and parameters the same?

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.

What are custom attributes in c#?

Attributes are metadata extensions that give additional information to the compiler about the elements in the program code at runtime.

What are custom attributes?

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.


2 Answers

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

like image 148
P.W Avatar answered Oct 30 '22 01:10

P.W


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.

like image 34
Tejendra Avatar answered Oct 30 '22 01:10

Tejendra