Overriding a method returning a reference to an array does not work in gcc, but works in clang/icx

Advertisements

I want to return a reference to an array in C++. I am referring to the getColor2 member function and its overrides in the example below.

I have a pure virtual member function in my base class ILed:

[[nodiscard]] virtual const uint8_t (&getColor2() const)[4] = 0

I have this method in a sub class HardwareLed:

[[nodiscard]] const uint8_t (&getColor2() const)[4] override;

I’d expect the latter function to override the former, but when using gcc (e.g. 13.2), I get these error message:

<source>:62:53: error: expected ';' at end of member declaration
   62 |   [[nodiscard]] const uint8_t (&getColor2() const)[4] override;
      |                                                     ^
      |                                                      ;
<source>:62:55: error: 'override' does not name a type
   62 |   [[nodiscard]] const uint8_t (&getColor2() const)[4] override;
      |   

Using the same source code, but with clang 17.0.1 or icx 2023.2.1 does not yield these errors and the application compiles successfully.

Here’s the complete example: https://godbolt.org/z/d7j7ozKbM

I could just resort to using the raw pointer to the array (perhaps with a struct and a reinterpret_cast instruction), but it seems not as good of a solution to me. getColor (without the 2) is implemented that way.

Also I’d file a bug in GCC, but I am not sure if they will let me (GCC bugzilla states, that I’ll get an invitation soon?) and they have a lot of known issues and I cannot exactly determine if this is one of them (e.g. incomplete types) as I am a bit of a C++ newbie.

Any help is greatly appreciated!

>Solution :

I would use std::array<uint8_t, 4>, see https://godbolt.org/z/h3TjxYv3b.

There is a pros – readability:

const std::array<uint8_t, 4>& getColor2() const; // is easier to read than
const uint8_t (&getColor2() const)[4];

using arr = uint8_t[4] also can be used: https://godbolt.org/z/Pbxhb8h3G.

arr& getColor2() const;

Leave a ReplyCancel reply