I have a memory leak in an OpenGL application i am creating. I cant seem to find that memory leak.
My question is, will this code be a memory leak:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class A{
A& doSometime(){
A *a = new A();
return *a; //Destructor wont be called, right?
}
};
void someFunction(){
A a = doSomethine();
}//..but destructor will be called here, or?
int main(){
for(int i = 0; i<99999999;i++)
someFunction();
return 0;
}
What i am not sure about is if I return an Object created with new like in the function doSomething above, when will the destructor be called, or do I need to call it my self.
*EDIT* changed the code abit, had placed main() and someFunction() in the class, and forgot an = *EDIT*
If you allocate something with new, it's destructor will not be called until you delete it.
Returning a reference to a new object is probably not a good idea. Passing ownership of objects makes it hard to keep straight who is responsible for deleting the object. It makes leaks far more likely.
What might be happening is you might be making copies of this new object. Those copies would be destructed (since they weren't new'd), but the original object will not be destructed.
Actually... it's very simple. Every new must have a matching delete. If you don't delete it, you get memory leaks.
Oh, I wasn't suggesting that you actually used it, just showing that new returns a pointer and that dynamically allocated objects must be manipulated by pointer only.