简体   繁体   中英

Declaring user-defined class types inside a C++ 'for' loop

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM