I have not worked with copy constructors/move constructors, and am trying to include them in a sparse matrix and vector library I am writing. I thought everything was peachy, everything was working well, operator overloading seemed to be successful, etc. Then I moved on to writing some basic iterative methods and was hit with debilitating memory errors. I believe it has to do with my constructors and assignment operators shown below:
/* Default constructor. */
CSC_Vector::CSC_Vector()
{
m_length = 0.;
m_values = new double[0];
}
/* Constructor for vector of given input length. Initializes to 0 default. */
/* Input: unsigned int - length */
CSC_Vector::CSC_Vector(const unsigned int & length)
{
m_length = length;
m_values = new double[length]();
}
/* Copy constructor. */
CSC_Vector::CSC_Vector(const CSC_Vector & vec)
{
// Copy vector length and values.
m_length = vec.m_length;
m_values = new double[m_length];
for(int i=0; i<m_length; i++) {
m_values[i] = vec(i);
}
}
/* Move constructor. */
CSC_Vector::CSC_Vector(CSC_Vector && vec)
{
// Move vector length and values to current object.
m_values = vec.m_values;
m_length = vec.m_length;
vec.m_values = nullptr;
vec.m_length = 0;
}
/* Copy assignment operator. */
CSC_Vector& operator=(const CSC_Vector & vec) {
cout << "Copy assign vector." << endl;
delete [] m_values;
m_length = vec.m_length;
m_values = new double[vec.m_length];
for(int i=0; i<m_length; i++) {
m_values[i] = vec(i);
}
return *this;
};
/* Move assignment operator. */
CSC_Vector& operator=(CSC_Vector && vec) {
cout << "Move assign vector." << endl;
delete [] m_values;
m_length = vec.m_length;
m_values = vec.m_values;
vec.m_length = 0;
vec.m_values = nullptr;
return *this;
};
The constructors are defined in the class .cpp file, and the assignment operators in the header file. A hopefully easy question for those with experience: are there problems in this code? I tried to write these based on things I've read on the internet and Stroustrup's addressing of it in the 4th edition, but somewhere I have done something seriously wrong.
I get two types of errors intermittently:
- incorrect checksum for freed object - object was probably modified after being freed.
- Seg fault I have tried valgrind, but it has not helped yet.