简体   繁体   English

在C ++ for循环内声明用户定义的类类型

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

Here are questions related to declaring built-in type variables inside a for loop: 以下是与在for循环中声明内置类型变量有关的问题:

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). 如果将在循环内声明它,则每次迭代都会调用构造函数和析构函数链,但是我们将具有限制范围(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). 如果在循环外声明了一个变量,则每次迭代将仅调用赋值运算符,但是可以在循环范围(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)? 如果最佳实践是在循环外声明变量,将循环置于作用域内以限制作用域(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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