Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always safe to replace a built-in array with a std/tr1/boost::array?

boost::array (or the tr1or 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;
...
like image 557
Martin Ba Avatar asked Oct 28 '11 10:10

Martin Ba


1 Answers

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.

like image 166
Kerrek SB Avatar answered Sep 22 '22 20:09

Kerrek SB