Here are questions related to declaring built-in type variables inside a for
loop:
Is there any overhead to declaring a variable within a loop? (C++)
Declaring Variables inside Loops, good practice or bad practice? (2 Parter)
But I would like to narrow down this subject and ask about declaring user-defined class type variables, which are inherited or made using composition and have non-trivial constructors/destructor with dynamic memory allocation/deallocation (new/delete).
a) int count = 0;
while(count < 1000000)
{
myClass myObj = some value;
++count;
}
b) int count = 0;
myClass myObj;
while(count < 1000000)
{
myObj = some value;
++count;
}
c) {
int count = 0;
myClass myObj;
while(count < 1000000)
{
myObj = some value;
++count;
}
}
- If I have to use a user-defined class variable inside a loop which is best practise for that, declare it inside or outside loop?
If it will be declared inside a loop the chain of constructors and destructors will be called per each iteration, but we will have advantages of restricted scope (a).
If a variable we had declared outside of loop, only the assignment operator will be called per each iteration, but this variable will be accessible out of loop scope (b).
Are compilers smart enough to optimize complex data types declaration as a loop local variable? Does memory allocation happen once and then the same space is reused on each iteration?
If best practices is, to declare variable outside a loop, is it a good idea to put the loop inside scope to restrict the scope (C)?
a
andb
actually do different things. Which do you want? – M.M