C++ Logo

std-discussion

Advanced search

[[maybe_unused]] classes

From: Stephan Bergmann <sbergman_at_[hidden]>
Date: Wed, 19 Apr 2023 09:52:13 +0200
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?

Received on 2023-04-19 07:52:19