13.4 What is the difference between deep copy and shallow copy? Explain how you would use each.
这道题问深拷贝和浅拷贝的区别。浅拷贝复制对象中所有的成员值到另一个对象中,而深拷贝不仅复制这些,还复制所有的指针对象,参见下面代码:
struct Test { char *ptr; }; void shallow_copy(Test &src, Test &dest) { dest.ptr = src.ptr; } void deep_copy(Test &src, Test &dest) { dest.ptr = (char*)malloc(strlen(src.ptr) + 1); strcpy(dest.ptr, src.ptr); }
本文转自博客园Grandyang的博客,原文链接:深拷贝和浅拷贝[CareerCup] 13.4 Depp Copy and Shallow Copy ,如需转载请自行联系原博主。