I want a template class to contain two template dynamic arrays as member variables. I use also a member function to assign to them values. However I got problem with the code and I do not know the reason (probably the syntax). What is the problem in the following code?
template<typename T>
class ArrayHolder
{
public:
ArrayHolder();
void setArrays( T [], T [],int,int);
private:
T *array1;
T *array2;
};
template<typename T>
ArrayHolderHolder<T>::setArrays(T firstarray[],T secondarray[] ,int N1, int N2)
{
array1 = new T[N1];
array2 = new T[N2];
}
After the initialization of the dynamic arrays in setArrays, what is the most effective to copy the arrays from the parameters (firstarray,secondarray) to them?
Here is one typo. The class name is
ArrayHolder, notArrayHolderHolder. Also, you didn’t write the return type.Since you cannot pass array (by value), it is better if you use pointer notation function in parameter list, and since it is class template, prefer defining the functions in the class itself:
By the way, instead of raw arrays, you could use
st::vectoras:And same in the parameter list of
setArraysas well. If you do so, thensetArraywould become this:Simple, isn’t it? No memory allocation, no deallocation!
Or even better, if you accept the arguments by value, then you could write this:
The last implementation is an idiomatic solution, preferred by library implementers.