c ++中的块内的局部变量的存储分配 [英] Storage allocation of local variables inside a block in c++
问题描述
我想知道编译器在什么时候为块中的局部变量分配存储。 goto和switch如何跳过构造函数? :
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?
编辑:
内置对象如int,char等
我得到的错误(ubuntu的g ++ 4.5):
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’
推荐答案
6.7 / 3:
可以转换为
块,但不能以初始化绕过
声明的方式。 A
程序从
a局部变量和自动
存储持续时间的点跳转到不在范围内的
点,其范围是
不成形除非变量具有POD
类型(3.9),并且没有
初始化程序(8.5)。
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).
重要的不是当存储被分配时,而是当构造函数被调用时。跳过构造函数的goto将是一个问题,这就是为什么它被禁止。 (没有初始化器的POD类型不需要任何构造,因此允许它们。)
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.)
这篇关于c ++中的块内的局部变量的存储分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!