template< typename ArrayType >
ArrayType *VectorToArray( ArrayType **p_ppThisBlock = NULL, vector< ArrayType > *p_vThisVector = NULL )
{
// If either of the parameters are NULL, return.
if( p_ppThisBlock == NULL || p_vThisVector == NULL )
{
return NULL;
}
elseif( p_ppThisBlock != NULL && p_vThisVector != NULL )
{
// Create the array which will store the vectors values.
p_ppThisBlock = new ArrayType[ p_vThisVector -> size( ) ];
// Initialize the new array.
for( unsigned uIndex( 0 ); uIndex < p_vThisVector -> size( ); uIndex++ )
{
p_ppThisBlock[ uIndex ] = p_vThisVector[ uIndex ];
}
// Return the memory block.
return p_ppThisBlock;
}
}
My question is: Do I need to free the memory allocated by p_ppThisBlock when the function ends? And is it relevant to return the block of memory that has been allocated by p_ppThisBlock.
If you delete it, you won't be returning anything. The caller will have to handle deletion when it's time, though. Notice that objects that don't have clear ownership are considered A Bad Thing because it's very easy to forget to delete them.
PS: just say no to hungarian notation. It makes your code much harder to read. Just look at the difference:
template<typename T>
T* vectorToArray(T* arr = NULL, std::vector<T>* vec = NULL) // fixed a bug; type of arr
{
// If either of the parameters are NULL, return.
if(arr == NULL || vec == NULL)
{
return NULL;
}
else // none of them is NULL, no need to check again
{
// Create the array which will store the vectors values.
arr = new T[vec->size()];
// Initialize the new array.
for(unsigned i = 0; i < vec->size(); ++i)
{
arr[i] = (*vec)[i]; // fixed a bug here
}
// Return the memory block.
return arr;
}
}
PPS: any reason the array has to be passed in and it can't be NULL? That's a guaranteed memory leak. And if you're operating directly into the array, why return it?