I have a custom template class Array<T>
, and am currently implementing the assignment operator.
However, I've come across a design decision: When assigning two arrays, must I require them to have the same size, or adjust the LHS Array
size to the RHS?
Pros and Cons of Requiring Equal Size
Pro
- Most of the time, the array is often thought of as a static container (there are
std::vector
, etc. for dynamic containers). - It's more efficient, because I do not have to reallocate; rather, I overwrite each element of the LHS.
Con
- It's a hassle for the user to do the work himself if he does intend to have a variable-length
Array
, plus it would be inefficient.
Code
Here are the implementations of the two versions I'm considering.
Equal Size
template <typename T>
bool JKArray<T>::operator=(const JKArray<T> & rhs)
{
if (this == *rhs) { return true; }
else
{
if (size_ != rhs.size_) { return false; }
else
{
for (int i = 0; i < size_; i++) { array_[i] = rhs.array_[i]; }
}
}
}
Unequal Size
template <typename T>
void JKArray<T>::operator=(const JKArray<T> & rhs)
{
if (this == *rhs) { }
else
{
if (size_ != rhs.size_)
{
delete [] array_;
size_ = rhs.size_;
array_ = new T[size_];
}
for (int i = 0; i < size_; i++) { array_[i] = rhs.array_[i]; }
}
}
Note
Regarding the implementation of Equal Size: I return false
if the size is not equal, and true
otherwise. Of course, I could use exceptions, however this is satisfactory for now.
I'm leaning towards making operator=
fail* if RHS is a different length than LHS.
I'd like to know what other's have done, and what the prefer. To avoid closing this on the basis of opinion-based, please give explanations as to why one might be preferred over the other.
*See 'Note' under 'Code'.
std::vector<>
. Otherwise it is not an array, it is surprising array at best. I'd expectsizeof(a)
to be the same as for C array, but in your code it will probably besizeof(T*)
. \$\endgroup\$