About replacing some "C-Array" into std::array
l.lunak at collabora.com
Fri Nov 22 16:35:00 UTC 2019
On Friday 22 of November 2019, julien2412 wrote:
> Taking a look at cppcheck report, I noticed this kind of reports:
> 132 useStlAlgorithm 398 style Consider using std::fill algorithm instead of
> a raw loop
Note that it says "style". Style in itself doesn't necessarily bring anything
besides, well, style.
> To use std::fill, we'd need to convert the C array into std::array.
No, we wouldn't: std::fill( array, array + 10, value );
> Reading https://coders-corner.net/2018/06/16/stdarray-vs-c-style-array/, it
> seems there's no real cons about this.
The summary is questionable. It omits section "std::array as method parameter
with variable size", which is actually a common use case for C
arrays. "Direct support of use in STL algorithms" is probably not true, given
that STL algorithms work just fine with pointers to C array elements, as
shown above. And "No memory overhead beyond what it needs to hold its
elements" is clearly not an advantage when comparing to C arrays, because
it's the same for C arrays.
Using std::array has some advantages over C arrays, no need to inflate the
list. If the author wanted the list to be longer, I have no idea why "not
bloody confusing for new developers" was skipped.
> The idea is not only to diminish cppcheck reports but above all try to gain
> some perfs (even little but multiplied by the number of calls...) by using
I think there wouldn't be any performance gain. Why should there be? Even the
page you linked says that one of advantages of std::array is that it has the
same performance as C array[*].
> Since we're at the beginning of 6.5, thought it could be relevant.
> The code change should be quite straight forward, so risk of regression
> should be low.
> Is there some kind of rule of thumb to decide between C array and
> std::array ?
Well, there are some that come to mind, such as "KISS" and "don't fix what is
not broken" :). There actually are places where C arrays may be better, such
as when the code is trivially simple, when interfacing with C libraries, or
when using STL actually makes the code worse[**].
But note that I'm not strictly opposed to this. I suppose there are places
where std::array can do better. I just think that such changes should not be
done blindly based on incorrect assumptions.
[*] The performance will be about the same only in optimized code, which the
article also forgets to mention.
[**] Which is not that hard given how clunky STL usage can be. I would
personally consider converting that transfer.cxx line to std::fill() to be a
regression in readability. If STL, then it should be std::array::fill().
l.lunak at collabora.com
More information about the LibreOffice