I'm decent at c++ but I've always been bad when it comes to pointers and memory. I've gotten into this situation where I don't know if there is a solution.
typedef unsigned long long ullong;
class MathClass { //This is just an example class
public:
MathClass() {num = new ullong[1]();}
MathClass operator+(MathClass b) { //This is not my actual function, just one that has the same problem
MathClass c;
c.num[0] = num[0] + b.num[0];
delete [] num;
num = NULL;
return c;
}
public:
ullong* num;
};
This would work for a situation like this.
MathClass a;
MathClass b;
for (int i = 0; i < 1000; i++) {
a = a + b;
}
Because I'm setting a equal to a + b, so when the + function is run it would set a equal to c and delete the old a num.
For a situation like this it would cause an error because I'm deleting b's num.
MathClass a;
MathClass b;
MathClass c;
for (int i = 0; i < 1000; i++) {
a = b + c;
}
If I did not delete num this would work, but that causes memory leaks. The memory for this easily goes over 100MB when I don't delete num. I'm sure the answer to this is simple but I can't figure it out.