Copy construction vs assignment operator
Jan 12, 2011 at 11:46pm UTC
On Wikipedia, there's this sample code for a copy constructor:
If we write our own copy constructor that performs a deep copy then this problem goes away.
1 2 3 4 5
Array(const Array& copy)
: size(copy.size), data(new int [copy.size])
{
std::copy(copy.data, copy.data + copy.size, data); // #include <algorithm> for std::copy
}
Here, we are creating a new int array and copying the contents to it.
However, since I've defined both a copy constructor and an assignment operator, would I need to copy the data from one object to another in the copy constructor?
1 2 3 4 5
// Copy constructor.
Array(const Array& toCopy)
: _rowSize(toCopy._rowSize),
_colSize(toCopy._colSize)
{ _ptr = new T[_rowSize*_colSize]; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
template <typename T>
const Array<T>& Array<T>::operator =(const Array& rhs)
{
// Prevent self assignment.
if (&rhs != this )
{
if (_rowSize != rhs._rowSize ||
_colSize != rhs._colSize)
{
delete [] _ptr;
_rowSize = rhs._rowSize;
_colSize = rhs._colSize;
_ptr = new T[_rowSize*_colSize];
}
for (int i=0; i<_rowSize*_colSize; i++)
_ptr[i] = rhs._ptr[i];
}
return *this ;
}
Or should I add
*this = toCopy;
to my copy constructor? I'm sort of confused, haha.
Jan 13, 2011 at 12:39am UTC
copy constructor and assignment are different concepts
copy constructor would only be called when you want to initiate an object
Jan 13, 2011 at 1:11am UTC
So then would just adding *this = toCopy;
within the copy constructor work?
Jan 13, 2011 at 1:39am UTC
Only if _rowSize, _colSize, and _ptr are properly initialized in the copy constructor (zero/null for all would work).
Topic archived. No new replies allowed.