对于标量值,赋值运算符似乎将右侧的值复制到左侧。这对于复合数据类型如何工作?例如,如果我有一个嵌套结构
struct inner {
int b;
};
struct outer {
struct inner a;
};
int main() {
struct outer s1 = { .a = {.b=1}};
struct outer s2 = s1;
}
- 赋值是否递归地深度复制值?
- 将结构传递给函数时是否会发生同样的情况?
通过实验,似乎确实如此,但是有人能指出该行为的规范吗?
最佳答案
没有“递归”;它复制该值的所有(值)位。当然,指针并不是神奇地遵循的,赋值运算符不知道如何复制指向的数据。
你能想到
a = b;
作为缩写
memcpy(&a, &b, sizeof a);
sizeof
当然是有误导性的,因为我们知道两边的类型是相同的,但我不认为 __typeof__
有帮助。
C11 规范草案说(在 6.5.16.1 简单分配,第 2 段中):
In simple assignment (
=
), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.
关于C:赋值运算符是否深复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56541914/