我正在写一个C编译器(以llvm为后端)练习,规则遵循the C11 standard §6.2.4 .
在浏览“对象的存储持续时间”部分时,一个案例让我感到困惑:
¶8 A non-lvalue expression with structure or union type, where the structure or union contains a member with array type (including, recursively, members of all contained structures and unions) refers to an object with automatic storage duration and temporary lifetime. Its lifetime begins when the expression is evaluated and its initial value is the value of the expression. Its lifetime ends when the evaluation of the containing full expression or full declarator ends. Any attempt to modify an object with temporary lifetime results in undefined behavior.
我无法想象这个案例讲的是什么情况,尤其是数组成员部分(作为具有临时生命周期的非左值,具有数组成员的结构与正常的非左值有什么区别吗?) 谁能给我一个代码示例来说明这一点?
最佳答案
其中没有数组的临时值不必引用具有自动(或实际上任何)存储持续时间的对象。数组是特殊的,因为数组到指针的转换,关于一个人可以在数组上执行的唯一有用的操作,隐含地要求它有一个地址,所以编译器必须为它分配内存(因此隐含地为整个对象包含它)。非数组左值没有地址。
struct a { int x; };
struct b { int y[2]; };
void foo(int*);
struct a one();
struct b two();
foo(&one().x); // not legal
foo(two().y); // legal, y has an address
关于c - C标准中生命周期规则的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56575413/