关于浅拷贝和深拷贝 [英] About Shallow copy and Deep copy

查看:99
本文介绍了关于浅拷贝和深拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是浅拷贝和深Cody?

What is Shallow copy and Deep Cody?

推荐答案

当你通过复制每个成员来复制类/结构的实例时,一般情况下你不会获得独立的副本,因为某些成员可能是指针,因此复制指针将使您的类/结构实例具有指向同一对象的两个指针。例如,如果您通过从源类/结构实例中取消引用指针来访问此对象,则可以从复制的实例访问同一对象,并显示已修改。



这是关于浅拷贝



要制作深拷贝(深度克隆),你需要通过使用相同的成员重新创建它们来递归复制成员指针指向的所有对象。这样,递归和完全复制操作的实际深度可能取决于对象的状态。



标准C ++运行时缺少 Reflection (我不是在这里谈论C ++ / CLI;这是一种不同的语言),你不能写一种通用的深拷贝方法。



其中一种方法是深层复制接口的实现(可以是一个抽象类,没有包含所有纯虚函数的数据,或者更确切地说是一个纯虚函数,如 DeepCopy ),并实现了这一点接口(通常,在类/结构本身中使用弱(或强)形式的多重继承),在所有继承的类中覆盖它。重写的深拷贝函数使用基本实现,依此类推。



-SA
When you copy an instance of class/structure by copying each member, in general case you won''t get independent copies, because some member might be pointers, so copying a pointer will give your to instances of the class/structures with two pointers pointing to the same object. If you, say, access this object by dereferencing the pointer from source class/structure instance, the same object can be accessed from the copied instance, and appear modified.

That was about the shallow copy.

To make a deep copy (deep clone), you would need to recursively copy all objects pointed by member pointers by recreating them with the same members. This way, the actual depth of recursion and full copy operation may depend on the state of the object.

As standard C++ runtime lacks Reflection (I''m not talking about C++/CLI here; this is a different language), you cannot write one universal deep copy method.

One of the approaches is implementation of the deep copy interface (which can be an abstract class, without data with all pure virtual functions, or, rather one pure virtual function, like DeepCopy), and implementing this interface (generally, using weak (or strong) form of multiple inheritance) in the class/structure itself, overriding it in all inherited classes. The overridden deep copy function uses the base implementation, and so on.

—SA


这篇关于关于浅拷贝和深拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆