C:赋值运算符是否深复制?

标签 c struct assignment-operator

对于标量值,赋值运算符似乎将右侧的值复制到左侧。这对于复合数据类型如何工作?例如,如果我有一个嵌套结构

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/

相关文章:

python - 对 Python 字节类型感到困惑

c++ - 这段代码中调用了哪个构造函数或赋值运算符?

c - 在运行时为文件分配唯一编号

c - OpenSSL 和 Apple Keychain 集成

c++ - 涉及串联和行号的宏替换

pointers - 不使用 reflrect 打印类型并创建新对象

c - 大文件支持在 C 编程中不起作用

ios - 在 Swift 3 中将结构写入 outputStream

c++ - C++0x 中的特殊成员函数

c++ - 包含指向派生模板类的基类指针的类的赋值运算符和复制构造函数