I don’t like questions with debug sessions and memory pointers pasted, but I am forced to ask one like that.
This is a question about invoking copy constructors. I know there are already answers about that, but I didn’t find anything that would solve my problem
I have a Matrix class:
class Matrix {
...
Matrix(const Matrix& other); // copy constructor, needed due to *data
private:
int *data;
};
Matrix contains a pointer to a static memory array data, so when I copy a Matrix, the static array should be also copied with mempy.
At one point, I want to copy Matrix object to another Matrix
debug("COPY BEGIN ");
debug("matricex before copy: " << &itsMatrix << " < " << &matrix);
itsMatrix = matrix;
debug("COPY END ");
debug("matricex after copy: " << &itsMatrix << " < " << &matrix);
The copy constructor should be invoked to copy the data. Apparently, instead of invoking the constructor, only values of the pointers are copied; later when both memory matrices are deleted, the same pointer to data is deleted twice and I have seg fault
Here is a debug session:
1: Matrix.cpp MATRUX EMPTY 0xbf901a28 with empty data 0
2: include/SubArrayMax.hpp COPY BEGIN
3: include/SubArrayMax.hpp matricex before copy: 0xbf901a28 < 0xbf901a3c
--- here I should see a copy constructor ---
--- but no debug string is printed ---
4: include/SubArrayMax.hpp COPY END
5: include/SubArrayMax.hpp matricex after copy: 0xbf901a28 < 0xbf901a3c
6: Matrix.cpp DELETE MATRIX 0xbf901a28 with data 0x81d0550
7: Matrix.cpp DELETE MATRIX 0xbf901a3c with data 0x81d0550
--- 0x81d0550 is deleted twice ---
and this is my copy constructor:
Matrix::Matrix(const Matrix& other) // copy construcutor
{
...
data = new mval_t[dim.w * dim.h];
memcpy(data, other.data, dim.w * dim.h * sizeof(mval_t));
debug("MATRIX " << this << " after copying, data " << data);
}
I know that copy constructors can be reduced by compiler, I tried -fno-elide-constructors and I also had seg fault.
Any hint why this happens? or maybe there is a better way to deal with copying objects with side effects?
No, in your case the assignment operator will be called.
Just define