FAQ 2.08 What are the basics of local objects within inner scopes?

graphics/new_icon.gif

C++ local objects die at the } in which they were created. This means they could die before the } that ends the function:

 #include "Car.hpp" void f() {   Car a;   for (int i = 0; i < 10; ++i) {     Car b;                                           <-- 1     // ...   }                                                  <-- 2   // ... }                                                    <-- 3 int main() {   f(); } 

(1) 1: Create a Car object on each iteration

(2) 2: Each iteration's b dies here

(3) 3: Object a dies here

The line labeled 1: Create a Car object on each iteration is within the loop body, so a distinct Car object that is local to the loop body is created on each iteration.

Note that C++ allows loop variables (int i in the example) to be created inside the for parameters. Loop variables that are declared this way are local to the loop: they cannot be accessed after the } that terminates the for loop. This means that a subsequent for loop could use the same loop variable. Note that this is a new language feature, and compilers may not uniformly support this rule in all cases.

Also notice that, unlike C, variables do not have to be declared right after a { . It is not only allowable but also desirable to declare C++ variables just before they are first used. Doing so allows their initialization to be bypassed if the section of code they are in is bypassed, and it allows the introduction of other runtime variables in their initialization if the code is not bypassed. So there is never anything to lose, indeed there is sometimes something to gain, by declaring at first use.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net