What is the scope of a 'while' and 'for' loop?

后端 未结 10 1667
有刺的猬
有刺的猬 2020-11-30 06:37

What is the scope of a while and for loop?

For example, if I declared an object within the loop, what is its behavior and why?

10条回答
  •  不知归路
    2020-11-30 06:54

    for( int i = 0; i < 10; ++i )
    {
      string f = "foo";
      cout << f << "\n";
    }
    // i and f are both "gone" now
    

    In the above sample code, both i and f are scoped within the {{ and }} When the closing brace is executed, both variables fall out of scope.

    The reason for this is simply that the Standard says so; that's how the C++ language works.

    As for motivation, consider that this can be used to your advantage:

    for( ...)
    { 
      std::auto_ptr obj(new SomeExpensiveObject);
    }
    

    In the above code, we are using an RAII smart pointer to "own" the expensive object we created within the loop. The scoping semantics of the for loop dictate that after each execution of the loop, the object that was created during that iteration will be destroyed.

提交回复
热议问题