In code I’m working on right now I have a method belonging to a class that itself creates an instance of another object to use within the method. Does the memory belonging to that object get automatically get released after the method returns and the object looses scope? Or will I be taking up more and more memory each time the method is called?
The code has this structure:
int Class::method(int input) {
Other_Class local_instance;
int i;
i = local_instance.do_something();
i *= input;
return i;
}
So will the memory belonging to local_instance be released upon returning from the method? Or will I have many instances of Other_Class clogging up memory?
Thanks very much for your time and help!
Well, to begin with,local_instanceis not an object of classOther_Classbut a function without arguments returningOther_class. This is also known as C++’s most vexing parse.EDIT: The code in the question has been corrected; the original version had
But let’s assume that this line actually read
Then yes, this object will be automatically get released at the end of the function. Note however that the same is not true for objects you allocate with
new, for those objects it is your responsibility to delete them when no longer needed.