I am trying to understand the following 2 versions of implementation of assignment operator, which is used to assign the other dynamic array to the the instance (class DoubleVector
) it was called with.
version 1.
DoubleVector& DoubleVector::operator= (DoubleVector other)
{
swap(vector_, other.vector_);
swap(size_, other.size_);
return *this;
}
version 2.
DoubleVector& DoubleVector::operator= (const DoubleVector& other)
{
double* newVector = new double[other.size_]; // (Try to) allocate new memory
for (int i = 0; i < other.size_; i++)
{
newVector[i] = other.vector_[i];
}
delete[] vector_; // After allocation succeeded we can delete the old array
size_ = other.size_;
vector_ = newVector;
return *this;
}
My questions are:
- For the version 1, is there any case that may be missed (e.g.
other.size_ = 0
)? - For the version 2, why we need to delete the old array (
delete[] vector_;
) after the allocation succeeded? Is it necessary? Furthermore, for the version 2, can I just directly assign
other
to the instance that "=" is called with? e.g.DoubleVector& DoubleVector::operator= (const DoubleVector& other) { for (int i = 0; i < other.size_; i++) { vector_[i] = other.vector_[i]; } size_ = other.size_; return *this; }