Thread: Deep and Shallow Copy

  1. #1
    Is Trying to Learn
    Join Date
    Mar 2006
    Location
    Hutton, Preston
    Posts
    215

    Deep and Shallow Copy

    Hi

    i have looked around on the internet for some information on deep and shallow copy but cannot find any information that helps so i was wondering if any of you could help me understand them

    id like to know what the difference is and how they uses the pointers to copy

    any information will be greatful thanks

  2. #2

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Suppose you have a class with a pointer member variable that should point to a dynamic array owned by the object. A shallow copy of the object would merely copy this pointer, so you would end up with two objects that have a pointer member variable pointing to the same array. A deep copy would iterate over the array and copy each element over to a new array.

    The compiler generated copy constructor and copy assignment operator performs a shallow copy, so in this case you would roll out your own versions to do a deep copy. Likewise, the compiler generated destructor would only destroy the pointer, so you would provide your own destructor to correctly delete[] the dynamic array.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. template and friend class
    By black_spot1984 in forum C++ Programming
    Replies: 3
    Last Post: 10-21-2008, 05:50 PM
  2. SO new to C++
    By black_spot1984 in forum C++ Programming
    Replies: 5
    Last Post: 09-30-2008, 01:32 AM
  3. Help me understand copying better
    By sh3rpa in forum C++ Programming
    Replies: 20
    Last Post: 11-12-2007, 09:34 PM
  4. Deep and Shallow Copying
    By peckitt99 in forum C++ Programming
    Replies: 4
    Last Post: 08-18-2007, 09:37 PM
  5. dynamic memory alloccation & returning objects
    By haditya in forum C++ Programming
    Replies: 8
    Last Post: 04-21-2005, 11:55 PM