posts - 134,comments - 22,trackbacks - 0
          http://www.devx.com/tips/Tip/13625

          Deep Copy and Shallow Copy
          The terms "deep copy" and "shallow copy" refer to the way objects are copied, for example, during the invocation of a copy constructor or assignment operator. In a deep copy (also called "memberwise copy"), the copy operation respects object semantics. For example, copying an object that has a member of type std::string ensures that the corresponding std::string in the target object is copy-constructed by the copy constructor of class std::string.
           
          class A
          {
          string s;
          };
          A a;
          A b;
          a=b; //deep copy

          When assigning b to a, the compiler-generated assignment operator of class A first invokes the assignment operator of class std::string. Thus, a.s and b.s are well-defined, and they are probably not binary-identical. On the other hand, a shallow copy (also called "bitwise copy") simply copies chunks of memory from one location to another. A memcpy() operation is an example of a shallow copy. Because memcpy() does not respect object semantics, it will not invoke the copy constructor of an object. Therefore, you should never use memcpy() to copy objects. Use it only when copying POD (Plain Old Data) types: ints, floating point numbers, and dumb structs.

          --------------------------------------------------------------------

          http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/oop-condestructors/shallowdeepcopy.html

          A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.

          A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disasterous consequences.

           原文地址 http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/oop-condestructors/shallowdeepcopy.html
          posted on 2009-12-10 15:44 何克勤 閱讀(219) 評論(0)  編輯  收藏 所屬分類: C/C++
          主站蜘蛛池模板: 漳州市| 义乌市| 黑河市| 长丰县| 涡阳县| 明光市| 栾川县| 临漳县| 尼勒克县| 蒙城县| 同德县| 吉水县| 家居| 武冈市| 大埔区| 兴宁市| 额敏县| 扎赉特旗| 彭州市| 萨嘎县| 登封市| 图们市| 玉环县| 高州市| 田阳县| 兴化市| 台安县| 德惠市| 临澧县| 防城港市| 崇义县| 兴化市| 双峰县| 南江县| 阿拉善盟| 东平县| 瑞金市| 新民市| 荔波县| 东辽县| 公安县|