gpt4 book ai didi

为给定范围创建一次复合文字

转载 作者:行者123 更新时间:2023-12-04 13:06:40 25 4
gpt4 key购买 nike

我对 N2346::6.5.2.5/15 很困惑和 N2346::6.5.2.5/16哪个国家(emp。我的)

15 EXAMPLE 8 Each compound literal creates only a single object in agiven scope

struct s { int i; };
int f (void)
{
struct s *p = 0, *q;
int j = 0;
again:
q = p, p = &((struct s){ j++ });
if (j < 2) goto again;
return p == q && q->i == 1;
}

The function f() always returns the value 1.

16 Note that if an iteration statement were used instead of anexplicit goto and a labeled statement, the lifetime of the unnamedobject would be the body of the loop only, and on entry next timearound p would have an indeterminate value, which would result inundefined behavior.


在我看来,这句话与标准的另一部分相矛盾。恰恰: N2346::6.5.2.5/5

If the compound literal occurs outside the body of a function, theobject has static storage duration; otherwise, it has automaticstorage duration associated with the enclosing block.


这意味着使用复合文字创建的块范围对象具有自动存储持续时间。 N2346::6.8/3 (我的):

The initializers of objects that have automatic storage duration, andthe variable length array declarators of ordinary identifiers withblock scope, are evaluated and the values are stored in the objects(including storing an indeterminate value in objects without aninitializer) each time the declaration is reached in the order ofexecution, as if it were a statement, and within each declaration inthe order that declarators appear.


所以即使 goto N2346::6.5.2.5/15 示例中的语句替换为迭代语句,每次到达时都应重新创建由复合文字创建的对象。
问题 : 为什么要更换 goto用迭代语句产生 UB?我的推理有什么问题?

最佳答案

even if the goto statement in the example of N2346::6.5.2.5/15 isreplaced with an iteration statement the object created by compoundliteral should be re-created each time it's reached.


你是对的 - 但重要的一点是块的结束标志着对象存储持续时间的结束。未定义的行为在 q = p 上触发在第二次迭代中,当 p不再有效,也在 return 上迭代语句之外的行。

更具体地说,该标准暗指这样的代码:
struct s { int i; };
int f (void)
{
struct s *p = 0, *q;
int j = 0;
for (j = 0; j < 2; j++)
{
q = p; // p is invalid in the second iteration
p = &((struct s){ j++ });
} // end of block - p is no longer valid!

// p points to an object whose storage duration has expired, and so this is undefined behavior
return p == q && q->i == 1;
}
你可以看到最后的 return引用一个对象的语句,该对象的存储持续时间在 for 结束时到期块,以及 q变量被分配给在第二次迭代中未定义的指针。 goto 用法之间的定义差异和一个迭代语句,如 for循环是在 for 内部创建的对象循环仅有效 在循环范围内 .

关于为给定范围创建一次复合文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69070100/

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