Why the destructor is called?

Hello everyone!

I'm coding an application and I don't understand why it isn't working. I've written a simple example to show you my problem:

Code:

`#include <iostream>`

using std::cout;

class test {

friend test operator+(test&, test&);

public:

test() {}

test(const int& s1, const int& s2);

double& operator ()(int i, int j) {return v[i][j];}

~test();

protected:

double** v;

int _s1, _s2;

};

int main() {

test t(4, 4);

test a(4, 4);

test b(4, 4);

for (int i = 0; i < 4; i++) {

a(i, i) = i;

b(i, i) = i + 2;

}

t = a + b;

for (int i = 0; i < 4; i++){

for (int j = 0; j < 4; j++)

cout << t(i, j) << " ";

cout << "\n";

}

system("pause");

return 0;

}

test operator+(test& a, test& b)

{

test z(a._s1, a._s2);

for(int i = 0; i < a._s1; i++){

for (int j = 0; j < a._s2; j++)

z(i, j) = a(i, j) + b(i, j);

}

return z;

}

test::test(const int& s1, const int& s2) {

v = new double*[s1];

for (int i = 0; i < s1; i++)

v[i] = new double[s2];

_s1 = s1;

_s2 = s2;

for (int i = 0; i < s1; i++){

for (int j = 0; j < s2; j++)

v[i][j] = 0.0;

}

}

test::~test() {

for (int i = 0; i < _s1; i++)

delete [] v[i];

delete [] v;

}

The problem is that when I do "t = a + b;" the "return z" in the function "test operator+(test&, test&);" it calls the destructor for z before it returns and this makes a crash because the variable t doesn't have anything.

Also, the destructor for "t" is called right after the return from the function causing another crash.

The interesting part is that if I adapt the code to sum vectors intead of matrices, it works!

Any help would be appreciated.

Thanks,

scherzo