how to delay destructor call

I am using operator to add two matrices stored inside matrix objects. I instantiate and initialize two matrices. Then I call operator to add them. But before adding the two matrices: m1 and m2 , their destructors gets called. When I start adding the matrices, since m2 matrix array has been deleted, it crashes. How can I force the destructors to get called after I add the two matrices together.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
C++ Syntax (Toggle Plain Text)
// calling matrix initialization and additionm1.initMatrix();m1.print();m2.initMatrix();m2.print();rslt = m1-m2; //operatormatrix matrix::operator +(matrix m1){         matrix rslt = getResultMatrix(rows, cols, 0);  	for(int n=0; n<iterations; n++)	{		for(int i=0; i<rows; i++)   		{   			for(int j=0; j<cols; j++)      			{         			rslt.m[i][j] = this->m[i][j]+m1.m[i][j];       			}    		}	} 	return rslt; }// destructormatrix::~matrix(){ 	delete[] this->m;}// calling matrix initialization and addition
m1.initMatrix();
m1.print();
m2.initMatrix();
m2.print();
rslt = m1-m2;

//operator
matrix matrix::operator +(matrix m1)
{
	
        matrix rslt = getResultMatrix(rows, cols, 0); 

	for(int n=0; n<iterations; n++)
	{
		for(int i=0; i<rows; i++)
   		{
   			for(int j=0; j<cols; j++)
      			{
         			rslt.m[i][j] = this->m[i][j]+m1.m[i][j];
				
      			}

   		}
	}
	
	return rslt;

}
// destructor
matrix::~matrix()
{
		
	delete[] this->m;
}
1. Pass the matrix m1 as a const reference on line 10.
2. Classes with pointers require you to define a copy constructor, assignment operator and destructor. You have only provided one of those.

OK, that was a rather terse reply. Apologies.

Because you do not define a copy constructor and assignment operator, when you pass the argument on line 10 by value, a copy is made. That copy is just a copy of the pointer this->m, and not the memory pointed by this->m. When that temporary copy is destroyed, the memory is deleted by the destructor. But you still have another object pointing to the same piece of memory.
My mistake. After debugging I found that the destructor is being called on result matrix just after the line:
matrix rslt = getResultMatrix(rows, cols, 0);
Destructor is not called on on m1 as I thought so.

I am instantiating a matrix object inside getResultMatrix like this:
matrix r;
then I populate 'r' and retun 'r' .
But when I look at the returned objectr 'rslt' just after getResultMatrix exection, I see nulls inside it. This may be the reason. How to fix this?
2. Classes with pointers require you to define a copy constructor, assignment operator and destructor.


Have you defined a copy constructor and an assignment operator for the matrix class yet? If so, what do they look like?
Topic archived. No new replies allowed.