boost::array
(or the tr1
or std
version) offer some nice additional features over a built-in array.
Up to now, our codebase only contains built-in arrays, for example (made up, but the style matches):
WORD m_lastReadFlags[FLAGS_MAX];
...
WORD flagBuffer[FLAGS_MAX];
if (getFlags(flagBuffer)) {
memcpy(m_lastReadFlags, flagBuffer, sizeof(m_lastReadFlags));
...
I think one'll get the idea.
Now, my question is, for those places in the code, where dropping in boost::array
would make sense (because of other changes made), is array
a 100% semantics preserving drop-in for the built in array? (Possible compiler errors are OK -- only silent behavioral changes are what's bothering me.)
That is, could above code be re-written (for example) to use:
boost::array<WORD, FLAGS_MAX> m_lastReadFlags;
and the memcpy (possibly adapted to use c_array()
or data()
) and other array-like access would remain the same? Yes, of course I could also replace the local buffer by an array and remove the memcpy
or use std::copy
or something like that, but the point of this question is about the compatibility of built-in arrays and the array class.
Update: One thing that's bothering me specifically is the places (like in the memcpy
case) where the built-in arrays are used as pointers. Will all occurences be caught by the
compiler / handled correctly?
What about assignment?
T arr1[N]; // or array<T, N>
T arr2[N]; // or array<T, N>
T* p1;
...
// Note, not all combinations will compile:
arr1 = arr2;
p1 = arr1;
arr2 = p1;
...
Yes, that should be fine, since the array
class is precisely a wrapper for an automatic array. It has the same access syntax with square brackets, and if you need to get at the pointer, you know how to do it. You can even use std::copy
everywhere and use iterators; chances are that that will be implemented by memcpy
anyway.
The array
class is of aggregate type (no non-trivial constructors/destructor/assignment), so you can initialize it with the traditional aggregate (brace) initializer, just like a plain array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With