Point to a pointer to a fixed-size array in the return statement

The easiest way to ask this question is with some code:

struct Point { int x; int y; int z; int* as_pointer() { return &x; } // works int (&as_array_ref())[3] { return &x; } // does not work }; 

as_pointer compiles, as_array_ref does not. The tidying seems to be in order, but I cannot understand the corresponding syntax. Any ideas?

+6
source share
3 answers

I found that array types are easier to handle with typedef:

 typedef int ints[3]; 

Then your as_array_ref should be written so that &as_array_ref() == &x .

The following syntaxes are possible:

  • simple C-style from int* to ints* :

    ints& as_array_ref() { return *( (ints*)(&x) ); }

  • C ++ style reinterpret_cast (suggested by @Mike Seymour - see also his answer). This is often considered best practice in C ++:

    ints& as_array_ref() { return *reinterpret_cast<ints*>(&x); }

  • Differs from int& to ints& , which is slightly shorter, but (for me) less intuitive:

    ints& as_array_ref() { return reinterpret_cast<ints&>(x); }

+7
source

To cast, you need to rethink the variable reference as an array reference:

 reinterpret_cast<int(&)[3]>(x); 

Keep in mind that using this gives undefined behavior; it will probably work on any reasonable implementation, but there is no guarantee that there will be no indentation between class members, while arrays are not padded.

+4
source

I think what you are trying to do would be easier (and clearer / cleaner) with combining.

+2
source

Source: https://habr.com/ru/post/943613/


All Articles