C语言 C中的浅拷贝和深拷贝
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15278194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shallow copy and deep copy in C
提问by ShadyBears
I tried googling this but only objected oriented languages pop up as results.
我尝试使用谷歌搜索这个,但只有面向对象的语言作为结果弹出。
From my understanding a shallow copy is copying certain members of a struct.
根据我的理解,浅拷贝是复制结构的某些成员。
so lets say a struct is
所以让我们说一个结构是
typedef struct node
{
char **ok;
int hi;
int yep;
struct node *next;
}node_t
copying the char** would be a shallow copy
复制 char** 将是一个浅拷贝
but copying the whole linked list would be a deep copy?
但复制整个链表将是一个深拷贝?
Do I have the right idea or am I way off? Thanks.
我有正确的想法还是我离题了?谢谢。
回答by
No. A shallow copy in this particular context means that you copy "references" (pointers, whatever) to objects, and the backing store of these references or pointers is identical, it's the very same object at the same memory location.
不。在这个特定上下文中的浅拷贝意味着您将“引用”(指针,无论如何)复制到对象,并且这些引用或指针的后备存储是相同的,它是相同内存位置的完全相同的对象。
A deep copy, in contrast, means that you copy an entire object (struct). If it has members that can be copied shallow or deep, you also make a deep copy of them. Consider the following example:
相比之下,深层复制意味着您复制整个对象(结构)。如果它有可以浅拷贝或深拷贝的成员,你也可以对它们进行深拷贝。考虑以下示例:
typedef struct {
char *name;
int value;
} Node;
Node n1, n2, n3;
char name[] = "This is the name";
n1 = (Node){ name, 1337 };
n2 = n1; // Shallow copy, n2.name points to the same string as n1.name
n3.value = n1.value;
n3.name = strdup(n1.name); // Deep copy - n3.name is identical to n1.name regarding
// its *contents* only, but it's not anymore the same pointer
回答by royal52
The copy constructor is used to initialize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory. In order to read the details with complete examples and explanations you could see the portion of this article about difference between Shallow and Deep copy constructors.
复制构造函数用于使用先前创建的同一类的对象来初始化新对象。默认编译器写了一个浅拷贝。当不涉及动态内存分配时,浅拷贝工作正常,因为当涉及动态内存分配时,两个对象将指向堆中的相同内存位置,因此为了解决这个问题,我们编写了深拷贝,因此两个对象都有自己的属性副本在记忆中。为了阅读带有完整示例和解释的详细信息,您可以查看本文中有关浅拷贝构造函数和深拷贝构造函数之间区别的部分。

