深度复制和浅复制的区别是什么?
当前回答
假设有两个数组arr1和arr2。
arr1 = arr2; //shallow copy
arr1 = arr2.clone(); //deep copy
其他回答
我从下面几句话中理解到。
浅拷贝将对象的值类型(int, float, bool)字段复制到目标对象中,对象的引用类型(字符串,类等)被复制为目标对象中的引用。在此目标引用类型将指向源对象的内存位置。
深度复制将对象的值和引用类型复制到目标对象的完整新副本中。这意味着值类型和引用类型都将被分配一个新的内存位置。
var source = { firstName="Jane", lastname="Jones" };
var shallow = ShallowCopyOf(source);
var deep = DeepCopyOf(source);
source.lastName = "Smith";
WriteLine(source.lastName); // prints Smith
WriteLine(shallow.lastName); // prints Smith
WriteLine(deep.lastName); // prints Jones
除了上述所有定义之外,还有一个最常用的深度复制,位于类的复制构造函数(或重载赋值操作符)中。
浅复制——>是当你没有提供复制构造函数时。在这里,只复制对象,但不复制类的所有成员。
深度复制——>是当您决定在类中实现复制构造函数或重载赋值,并允许复制类的所有成员时。
MyClass& MyClass(const MyClass& obj) // copy constructor for MyClass
{
// write your code, to copy all the members and return the new object
}
MyClass& operator=(const MyClass& obj) // overloading assignment operator,
{
// write your code, to copy all the members and return the new object
}
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 article C++ constructors.
假设有两个数组arr1和arr2。
arr1 = arr2; //shallow copy
arr1 = arr2.clone(); //deep copy
推荐文章
- 在支持循环和函数的语言中,是否存在“goto”的合法用例?
- 为什么不使用异常作为常规的控制流呢?
- 什么是序列化?
- 如何从表中导出所有数据到可插入的sql格式?
- 我如何复制一个哈希在Ruby?
- 每个递归都可以转换成迭代吗?
- 什么是ORM,它是如何工作的,我应该如何使用它?
- 我能在服务器端应用程序(PHP、Ruby、Python等)上读取URL的哈希部分吗?
- 多少个参数是太多?
- Git复制文件保存历史
- 对于不可变集合上的非突变“add”方法,最好的名称是什么?
- foo到底是什么意思?
- MySQL:在同一个MySQL实例上克隆MySQL数据库
- foreach和map有区别吗?
- 设计模式:工厂vs工厂方法vs抽象工厂