Search code examples
c++c++17compiler-warningscompiler-bug

[[maybe_unused]] on member variable, GCC warns (incorrectly?) that attribute is ignored


In the following example:

struct Foo {
    [[maybe_unused]] int member = 1;
    void bar() {
        [[maybe_unused]] int local = 0;
    }
};

int main(int argc, char* argv[]) {
    Foo f{};
    f.bar();
    return 0;
}

GCC emits a warning where Clang and MSVC do not:

warning: 'maybe_unused' attribute ignored [-Wattributes]
     [[maybe_unused]] int member = 1;

As far as I can tell, this should be legal (and not ignored by the compiler). According to the standard:

10.6.7 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.
...

I hate to swing around the "compiler bug" hammer, but I'm not sure what else it could be in this case.

Does anyone have any insight?


Solution

  • Any attribute can be "ignored by the compiler" for any reason, except where the standard says otherwise (such as using an attribute in a location where it is expressly forbidden).

    GCC isn't saying you can't put one there; it's saying that putting one there won't do anything, because they probably don't warn about maybe-unused member variables.