008 浅拷贝与深拷贝

/*
目录:
   一 思考
   二 浅拷贝
   三 深拷贝
*/

一 思考

浅拷贝
    1 原因: 
        (1) a类拥有堆空间。
        (2) b类,b = a;
        (3) 编译器无法区分b类是否要申请堆空间,且b类堆空间要拷贝a类堆空间数据。
        (4) 只能b类某指针指向a类堆空间数据。
 
深拷贝
    1 目的: 编译器对类操作堆数据不完善,需要自己编写


二 浅拷贝

#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;        // 浅拷贝
    c1.~CTest();    // 空间已释放 : c1 - m_pAddr
    c2.~CTest();    // 报错 : 无法释放已释放空间

    return 0;
}


三 深拷贝

#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;        // 深拷贝
    c1.~CTest();    // 释放空间 - c1堆中
    c2.~CTest();    // 释放空间 - c2堆中

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/huafan/p/11620998.html