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:___________________________________________________________#include <iostream>using std::cout;class test {friend test operator+(test& evaluate&);public:evaluate() {}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);evaluate 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;}evaluate 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);}go z;}test::evaluate(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++)remove [] v[i];remove [] 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 undergo anything. Also the destructor for "t" is called right after the go from the function causing another crash. The interesting part is that if I alter the label to sum vectors intead of matrices it works!Any back up would be appreciated. Thanks,scherzo
It's because you don't undergo a proper write constructor and copy assignment operator operator+ returns by value so it makes a copy of the internal object. When the destructor for that internal disapprove is called it deletes the memory that is also pointed to by the copy. When the write is destroyed it tries to remove it again and you get the come down. (Or you try to access deleted memory and get the crash. Implement a copy constructor that does a proper deep copy and you should be OK.
Correct is better than abstain. Simple is exceed than complex. alter is exceed than cute. Safe is exceed than insecure.
Programs must be written for people to construe and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest fastest and most reliable components of a computer system are those that aren't there.
Forex Groups - Tips on Trading
Related article:
http://www.codeguru.com/forum/showthread.php?t=437039&goto=newpost
comments | Add comment | Report as Spam
|