Shallow copy and deep copy 008

 

/ * 
Directory: 
   a thinking 
   two shallow copy 
   triple deep copy 
* /

 

A thinking

Shallow copy
     1 reasons: 
        ( 1 ) A class has heap space. 
        ( 2 ) class b, b = a; 
        ( . 3 ) b-compiler can not distinguish whether the application stack space, and the b-type reactor space to copy a heap data. 
        ( 4 ) only a pointer to a class b class heap space data. 
 
Deep copy 
    1 Objective: compiler stack data class imperfect operation, it is necessary to write their own

 


Two shallow copy

#include "stdafx.h"
#include <iostream>
using namespace std;

class CTest
{
public:
    CTest()
    {
        m_pAddr = new char(0);
    }
    ~CTest()
    {
        delete[]m_pAddr;
    }

    void Set()
    {
        m_pAddr = new char[5];
        char szStr[] = "1234";
        strcpy_s(m_pAddr, 5, szStr);
    }
    void Pint()
    {
        cout << m_pAddr << endl;
    }
    
    int GetLength()const
    {
        return strlen(m_pAddr);
    }

private:
    char *m_pAddr;
};


int main(int argc, char *argv[], char **envp)
{
    CTest c1;
    c1.Set();
    c1.Pint();

    CTest c2;
    c2 = c1;        //Shallow copy 
    . CTest C1 ~ ();     // space released: C1 - m_pAddr 
    C2 ~ CTest ();.     // error: not release space freed 

    return  0 ; 
}

 


Three deep copy

#include "stdafx.h"
#include <iostream>

using namespace std;

class CTest
{
public:
    CTest()
    {
        m_pAddr = new char(0);
    }
    ~CTest()
    {
        delete[]m_pAddr;
    }

    void Set()
    {
        m_pAddr = new char[5];
        char szStr[] = "1234";
        strcpy_s(m_pAddr, 5, szStr);
    }
    void Pint()
    {
        cout << m_pAddr << endl;
    }
    
    int GetLength()const
    {
        return strlen(m_pAddr);
    }

    CTest& operator=(const CTest &str)
    {
        int nLength = str.GetLength();
        int nThisLength = strlen(this->m_pAddr);
        if (nThisLength < nLength)
        {
            delete[] m_pAddr;
            m_pAddr = new char[nLength + 1];
            strcpy_s(m_pAddr, nLength + 1, str.m_pAddr);
            return *this;
        }
        strcpy_s(m_pAddr, nThisLength, str.m_pAddr);
        return *this;
    }
private:
    char *m_pAddr;
};

int main(int argc, char *argv[], char **envp)
{
    CTest c1;
    c1.Set();
    c1.Pint (); 

    CTest C2;
    c2 C1 =;         // deep copy 
    C1 ~ CTest ();.     // free space - c1 stack 
    C2 ~ CTest ();.     // free space - c2 heap 

    return  0 ; 
}

 

Guess you like

Origin www.cnblogs.com/huafan/p/11620998.html