if we repeat while loop, every time when we get into the for loop, an i will created and used? but what about the old i? Is is destroyed? I am worrying about the memory will be used up if I do this. Thanks.
if we repeat while loop, every time when we get into the for loop, an i will created and used? but what about the old i? Is is destroyed?
For basic types like int this doesn't matter because construction/destruction does not require any work. However for complex types which are expensive to construct/destruct, you want to avoid declaring them in loop bodies for this very reason.
I am worrying about the memory will be used up if I do this.
It will not use any additional memory. The memory the function uses is all allocated "up front" at the start of the function. The "new" 'i' will likely use the same space in memory as the old 'i', despite it having been destructed/reconstructed.
This is kind of an oversimplification of how the stack works... but the point is it won't use more memory... but for complex types it will require more CPU time to recreate and destroy it every loop.
Thanks, if it is a class type, and no destructor are explicitly defined. Will it be destroyed? Thanks.
If you did not define explicitly the destructor then the compiler will define it implicitly. Otherwise the compiler will issue a compilation error because it will be unable to generate the object code.