我想知道编译器在哪一点为块内的局部变量分配存储空间.goto和switch如何跳过构造函数?:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然上面的代码不适用于用户定义的对象,但如果我用内置对象替换它们,它就可以工作.这是为什么?
编辑:内置对象,如int,char等.我得到的错误(在ubuntu上的g ++ 4.5):
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’
Run Code Online (Sandbox Code Playgroud)
Ala*_*kes 13
6.7/3:
可以转换为块,但不能以初始化绕过声明的方式.从具有自动存储持续时间的局部变量不在范围内的点跳转到其在范围内的点的程序是不正确的,除非该变量具有POD类型(3.9)并且在没有初始化器(8.5)的情况下声明.
重要的不是在分配存储时,而是在调用构造函数时.跳过构造函数的goto将是一个问题,这就是它被禁止的原因.(没有初始化器的POD类型不需要任何构造,因此允许它们.)