0
votes

Here are questions related to declaring built-in type variables inside a for loop:

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;
        }
    }
  1. 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).

  1. 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?

  2. 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)?

1
If the class has a user-defined assignment operator or constructor, then a and b actually do different things. Which do you want?M.M
The declaration of a variable costs very little if nothing in performance as the compiler does the necessary space allocation at compile time. But the initialization of the variable does cost. So, it is more a question of what you want. Should the variable be initialized in each loop or should it be initialized once before the loop. This is no question of style, but what you want to achieve.nv3
@Matt McNabb I need to use a local variable inside the loop so I want to know what is best practice for this case declare outside of loop or inside ?T M
On a threads I have mentioned, the best practice for built in types is declare and use inside a loop, so I want to understand what is best practice for user defined types.T M

1 Answers

1
votes

If you want to destroy a variable immediately after the loop, you can enclose the loop with an additional scope. This will restrict the object's scope and eliminate the overhead of multiple construction and destruction.

{
    Object object;
    for (int i = 0; i < 100000; ++i) {
        // ....
    }
} // 'object' will be destroyed