In the sample code below ComputeSomething() returns a reference to an array.
I was asked to use C++ core guidelines (NuGet package on MSVC toolchain) as an extra static analysis tool.
On the return line of ComputeSomething()
the static analysis tool warns that there is an array to pointer decay. I assume the intent would be to change it in order to make the decay explicit (something like &(computed_values[0])
) but then that would defeat the point of returning an array by reference.
Is this a valid warning or is it noise, for this specific use-case of returning an array by reference?
(assumes a C++98 constraint)
float (&ComputeSomething( const seed_t(&seed_data)[num_of_elems_seeded] ))[num_of_elems_calculated]{
static float computed_values[num_of_elems_calculated];
// do something...
return computed_values;
}
For the method below:
float (&ComputeSomething())[num_of_elems_calculated]{
static float computed_values[num_of_elems_calculated];
// do something...
return computed_values;
}
Unlike what is probably happening in the static analysis tool, the potential array to pointer decay is not determined inside the method but instead when the caller calls the function:
// expected to decay
float *some_computation = ComputeSomething();
// not expected to decay to pointer
float (&safer_computation)[num_of_elems_calculated] = ComputeSomething();
Thanks to @Galik for his input on this.