F
Frederick Gotham
What's the canonical way to copy an array in C++?
If we're copying a POD, we can use memcpy (but there could be a more
efficient alternative if we know that the blocks are suitably aligned).
Regardless of whether the array consists of POD's, we could use a loop such
as:
#include <cassert>
template<class T>
void CopyArray(T *pdest, T const *psource, T const *const psover)
{
assert(pdest);
assert(psource);
assert(psover); /* Contraversey here! */
assert(psover > psource);
do
{
*pdest++ = *psource++;
} while(psource != psover);
}
#define ARRLEN(arr) (sizeof(arr)/sizeof*(arr))
#define POVER(arr) ((arr) + ARRLEN((arr)))
int main()
{
int array1[5] = {1,2,3,4,5};
int array2[5];
CopyArray(array2,array1,POVER(array1));
}
However, I presume that there's a Standard Library function for doing this?
What's the most efficient method?
Also, how do you go about copy-constructing an array? Seems to me that
you'd have to use "aligned_storage", and then do a loop which uses
"placement new". I wonder why the following is disallowed:
int main()
{
int arr1[] = {1,2,3,4,5};
int arr2[] = arr1;
}
If we're copying a POD, we can use memcpy (but there could be a more
efficient alternative if we know that the blocks are suitably aligned).
Regardless of whether the array consists of POD's, we could use a loop such
as:
#include <cassert>
template<class T>
void CopyArray(T *pdest, T const *psource, T const *const psover)
{
assert(pdest);
assert(psource);
assert(psover); /* Contraversey here! */
assert(psover > psource);
do
{
*pdest++ = *psource++;
} while(psource != psover);
}
#define ARRLEN(arr) (sizeof(arr)/sizeof*(arr))
#define POVER(arr) ((arr) + ARRLEN((arr)))
int main()
{
int array1[5] = {1,2,3,4,5};
int array2[5];
CopyArray(array2,array1,POVER(array1));
}
However, I presume that there's a Standard Library function for doing this?
What's the most efficient method?
Also, how do you go about copy-constructing an array? Seems to me that
you'd have to use "aligned_storage", and then do a loop which uses
"placement new". I wonder why the following is disallowed:
int main()
{
int arr1[] = {1,2,3,4,5};
int arr2[] = arr1;
}