Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a reference array from a const member function

How do I return an array reference from a const member function?

class State{
    Chips (&arr() const)[6][7] { return arr_; }
    Chips val() const { return val_; }
}

Invalid initialization of reference of type 'Chips (&)[6][7]' from expression of type 'const Chips [6][7]'

Thank you.

like image 535
david Avatar asked May 08 '26 03:05

david


1 Answers

You got the syntax right, but if arr_ is an immediate member of the class (and it probably is), then you simply can't return a non-cost reference to this member. Inside the above arr method, member arr_ is seen as having const Chips[6][7] type. You can't use this type to initialize a reference of Chops (&)[6][7] type since it would break const-correctness. In order for the above to compile you'd need a const on the returned reference as well

...
const Chips (&arr() const)[6][7] { return arr_; }
...

But in any case, you'll be much better off with a typedef

...
typedef Chips Chips67[6][7];
const Chips67 &arr() const { return arr_; }
...
like image 98
AnT Avatar answered May 10 '26 19:05

AnT