C++ Logo


Advanced search

Re: [[maybe_unused]] classes

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Wed, 19 Apr 2023 10:02:00 +0100
On 19 April 2023 08:52:13 BST, Stephan Bergmann via Std-Discussion <std-discussion_at_[hidden]> wrote:
>C++20 [dcl.attr.unused]/2,4 state:
>"The attribute may be applied to the declaration of a class, a typedef-name, a variable (including a structured binding declaration), a non-static data member, a function, an enumeration, or an enumerator.
>"Recommended practice: For an entity marked maybe_unused, implementations should not emit a warning that the entity or its structured bindings (if any) are used or unused. [...]"
>So if a class is annotated [[maybe_unused]] I would expect compilers to suppress warnings about that class itself not be used anywhere. I would not expect compilers to suppress warnings about variables of that class type being unused.
>Yet, for some test code
>> namespace {
>> struct S1 {}; // expected-warning{{unused}}
>> struct [[maybe_unused]] S2 {};
>> }
>> struct S3 {};
>> struct [[maybe_unused]] S4 {};
>> void f() {
>> S3 s3a; // expected-warning{{unused}}
>> [[maybe_unused]] S3 s3b;
>> S4 s4a; // expected-warning{{unused}}
>> [[maybe_unused]] S4 s4b;
>> }
>and popular Clang, GCC, and MSVC compilers (see <https://godbolt.org/z/vdfG6bT5s>):
>* None of the three compilers warn about either of the two unused types S1 and S2. (Which is fine, of course. Compilers don't /have/ to warn about all kinds of unused entities in the first place.)
>* All three compilers warn about the unused variable s3a. (Which is fine.)
>* But only MSVC warns about the unused variable s4a. Both Clang and GCC appear to interpret the [[maybe_unused]] on S4 to extend to variables of that type. Should that be considered a violation of the recommended practice on the part of Clang and GCC?

I think you are right that gcc and clang does not implement the recommended practice as worded in the standard.

They seem to interpret the attribute similarly to __attribute__((unused)). The gcc documentation attaches the following semantics for this attribute:

"When attached to a type (including a union or a struct), this attribute means that variables of that type are meant to appear possibly unused. GCC does not produce a warning for any variables of that type, even if the variable appears to do nothing. This is often the case with lock or thread classes, which are usually defined and then not referenced, but contain constructors and destructors that have nontrivial bookkeeping functions. "


The documentation even gives reasoning why this is useful.

I would argue that this behaviour is much more useful than the recommended practice in the standard wording, and this is a bug in the standard.

I don't find an equivalent annotation for MSVC, although it could be similarly useful for these kinds of guard types.


Received on 2023-04-19 09:02:07