Shallow Vs Deep Copying
Table of Contents

Shallow Copying

A shallow copy means that C++ copies each member of the class individually using the assignment operator.

** Example 1**: For classes that do not contain any dynamically allocated memory, this works very well.

class Cents
{
private:
    int m_nCents;
public:
    Cents(int nCents=0)
    {
        m_nCents = nCents;
    }
};
class MyString
{
private:
    char *m_pchString;
    int m_nLength;
 
public:
    MyString(char *pchString="")
    {
        // Find the length of the string
        // Plus one character for a terminator
        m_nLength = strlen(pchString) + 1;
 
        // Allocate a buffer equal to this length
        m_pchString= new char[m_nLength];
 
        // Copy the parameter into our internal buffer
        strncpy(m_pchString, pchString, m_nLength);
 
        // Make sure the string is terminated
        m_pchString[m_nLength-1] = '\\0';
    }
 
    ~MyString() // destructor
    {
        // We need to deallocate our buffer
        delete[] m_pchString;
 
        // Set m_pchString to null just in case
        m_pchString = 0;
    }
 
    char* GetString() { return m_pchString; }
    int GetLength() { return m_nLength; }
};

The following code will crash

int main()
{
 MyString cHello("Hello world!");
 {
  // call the MyString constructor which allocates memory and sets cHello.m_pchString to point to it, and then copies the string "Hello world" into it.
 
   MyString cCopy = CHello; // use default copy constructor. C++ will do a shallow poitner copy and it will copy the address of the pointer, the address of cHello.m_pchString is copied into cCopy.m_pchString. So cCopy.m_pchString and cHello.m_pcString are now pointing to the same piece of memory.
 
+ Deep copying
A deep copy duplicates the object or variable being pointed to so that the destination receives it's own local copy.
Doing deep copies requires that we write our own copy constructors and overloaded assignment operators.
 
[[code type="Cpp"]]
// Copy constructor
MyString::MyString(const MyString& cSource)
{
    // because m_nLength is not a pointer, we can shallow copy it
    m_nLength = cSource.m_nLength;
 
    // m_pchString is a pointer, so we need to deep copy it if it is non-null
    if (cSource.m_pchString)
    {
        // allocate memory for our copy
        m_pchString = new char[m_nLength];
 
        // Copy the string into our newly allocated memory
        strncpy(m_pchString, cSource.m_pchString, m_nLength);
    }
    else
        m_pchString = 0;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.