Frederick Gotham posted:
I want to copy an array of objects.
If it were C, I'd simply do:
memcpy( target_array, source_array, sizeof target_array );
However, this won't suffice for objects in C++.
Does the C++ STL provide a facility for copying arrays of objects, or
must I write my own loop?
I'll be more specific.
I want to copy-construct an entire array of objects, rather than default-
construct a new array and subsequently perform assignments.
It would be great if the STL provided such a facility. At the moment, I
have to use the following code... but it's inefficient if I end up
dealing with something simple like an array of short's.
/* The following function takes the address of a raw
byte buffer, in which it shall construct the new
array */
template<class T>
T *CopyConstructArray( unsigned char * const p_target,
const T *p_source,
unsigned long len )
{
unsigned char *p = p_target;
do
{
new(p) T(*p_source);
} while ( p += sizeof(T), ++p_source, --len );
return reinterpret_cast<T*>(p_target);
}
template<class T>
void ArbitraryFunc( const T *p_start, const T *p_over )
{
unsigned long const len = p_over - p_start;
unsigned char * const p_buf = new unsigned char[ sizeof(T) * len ];
T *p_array = CopyConstructArray( p_buf, p_start, len);
/* Now p_array points to the copy-constructed array */
/* More code */
}
int main()
{
std::string array[64];
ArbitraryFunc( array, *(&array + 1) );
}