Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storage allocation of local variables inside a block in c++

I want to know at which point the compiler allocates storage for local variables inside a block. How does goto and switch jump past a constructor? :

class Tree {/*...*/}
...
void foo (int i){
if (i < 10) goto label; //illegal: cannot jump past a ctor
 Tree t (45);
 label: 
   switch (i){
      case 1:
            Tree t2 (45);
            break;
      case 2: //illegal: cannot jump past ctor 
            Tree t3 (45);
            break;
   }
}

While the above code does not work for user-defined objects it works if i replace them with built-in objects. Why is that?

Edit: Built in objects like int, char, etc. The errors i get (g++ 4.5 on ubuntu):

jumpPastConstructor.c++: In function ‘void foo(int)’:
jumpPastConstructor.c++:26:3: error: jump to label ‘label’
jumpPastConstructor.c++:24:20: error:   from here
jumpPastConstructor.c++:25:10: error:   crosses initialization of ‘Tree t’
jumpPastConstructor.c++:31:16: error: jump to case label
jumpPastConstructor.c++:29:25: error:   crosses initialization of ‘Tree t2’
like image 717
badmaash Avatar asked Jun 30 '11 16:06

badmaash


1 Answers

6.7/3:

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).

What matters is not when the storage is allocated, but when the constructor is called. A goto that jumped past a constructor would be a problem, which is why it's banned. (POD types with no initialiser don't need any construction, so they're allowed.)

like image 89
Alan Stokes Avatar answered Feb 20 '23 14:02

Alan Stokes