Search code examples
c++arraysreferenceoverhead-minimization

how to static cast raw array into struct that only consists of reference to array


I have a performance-critical piece of code where an operator shall return a wrapped reference to a raw array:

struct A{
   float (&p)[32]; // << this is the only attribute of A; you may change the type of p into float* but iff there is no other possible solution.
   // ... here follow member-functions of A
};
struct B{
   float (*p)[32]; // << this is mandatory
   A& operator[](size_t i){ return static_cast<A>(p[i]); } // << critical line
};

There is no option to replace B with an array of A, because B references data from raw external code. I could circumvent the issue by changing the member functions of A to non-member functions on float[32], but then I'd have to refactor a significant portion of existing code.

Of course, the cast in the critical line cannot be made. But, I want to accept neither the redundancy of creating an array of A, nor the overhead of constructing (and eventually destructing) an instance of A for every call of operator[].

So how can it be done. Please provide functioning code that achieves the purpose with minimum (ideally none at all) overhead.


Solution

  • A only has a single member of reference type. This is extremely easy to construct/destruct. It should have the exact same overhead as returning a pointer.

    Just construct a new A object with every invocation:

    struct B{
       float (*p)[32]; // << this is mandatory
       A operator[](unsigned i){ return A{p[i]}; } // << critical line
    };
    

    And there will be no overhead versus using non-member functions on float[32]: https://godbolt.org/z/Md6TP7PPP