While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I’m aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I’m puzzeled about.
Lets say you have a for loop:
for(int i = 0; i < 10; i++)
{
MyObject obj(file);
obj.doSomething();
}
Now the problem is that if the Object contains state, it keeps it state (stays the same object) while iterating through the iterations from 1 til 10. Maybe coming from a Java/C# background gets me on the wrong path. But I only see two ways of solving this:
- Using dynamic memory.
- Not giving file to the constructor but instead to the method
doSomething(file)but this isn’t very nice if you have more than one method manipulating the file object e.g.doSomethingElse(file).
So what do you guys do in such a situation, or do you never get yourself in such a situation at all?
Update:
Turns out i misunderstood and it is working as expected. Check the awnsers below! Thanks everyone
In the code you have posted, obj does not maintain any state between iterations.
In that example, obj is a different object every time. It may be using the same ‘stack’ memory location as the previous object, but the class destructor and constructor are called between iterations.
If you wish to have the object only be constructed once and used repeatedly, construct before the loop.