gpt4 book ai didi

范围引起的对象的 C++ 条件存储分配

转载 作者:搜寻专家 更新时间:2023-10-31 01:06:22 24 4
gpt4 key购买 nike

目前我正在阅读 Think in C++

我对对象的条件存储分配感到困惑。

如下面的代码,gotoswitch 生成警告或错误

但是 if-else 工作正常,它在执行期间有条件地通过。

那么为什么 if-else 没有警告或错误?

/* crosses initializaion error */  
#include <iostream>
using namespace std;
class X {
public:
X();
};
X::X() {}

void f(int i) {
if (i > 2) {
X x1;
} else {
X x2; // why conditionally executed works fine?
}
if (i > 2) {
goto jjump1;
}
//X x3; // error coused by goto
{X x3; //works fine}
jjump1:
X x4;
switch(i) {
// case 1: X x5; break;
//case 2: X x6; break; // error coused by switch
{case 1: X x5; break;}
{case 2: X x6; break;}// solved

}
}
int main() {
f(1);
return 0;
}

更新:

C++这样做是为了保证一个对象不能被创建,除非它也被初始化。但是在if-else的情况下,它的两个部分怎么可能是初始化为只有一部分会通过?

因为 C++ 遵循 C 中的做法,在该作用域的左大括号处为该作用域分配存储空间。

这是我的想法(我不知道哪里出了问题..):

但是对于switchgoto也是一样的,只有token case需要初始化,但是有crosses initialization error。 if-elseswitch 都遵循仅初始化 token 分支。

最后,我想出了关键字是scope由于 C++ 遵循 C 中的做法,即在该作用域的左大括号处为该作用域分配存储空间。因此,程序从具有自动存储持续时间的变量所在的点跳转 87不在范围内到它在范围内的点格式错误,除非变量具有标量类型、具有平凡默认构造函数和平凡析构函数的类类型、这些类型之一的 cv 限定版本或数组上述类型之一并且在没有初始化器的情况下声明规则确保变量在分配后初始化

谢谢大家

最佳答案

不允许跳过变量的声明,除非它是标量或具有普通的默认构造函数,这在 draft C++ standard 中有所介绍。 6.7 部分:

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps87 from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).

switch 的情况下,避免此问题的一种方法是在每个标签处使用 {} 创建一个范围,如下所示:

switch(i)
{
case 1: { X x5; break; }
case 2: { X x6; break; }
}

关于范围引起的对象的 C++ 条件存储分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20963288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com