C++-shallow copy, deep copy

This blog is just a simple record, so that you have a simple understanding process when you see this program, without any drawing explanation

#include <iostream>
using namespace std;

//前置声明
class string;

//计数器
class string_rep
{
    
    
    friend class String;
public:
    //构造函数
    explicit string_rep(const char* str = ""):m_count(0)
    {
    
    
        m_data = new char[strlen(str) + 1];
        strcpy(m_data,str);
    }
    //拷贝构造函数
    string_rep(const string_rep &rep):m_count(0)
    {
    
    
        //浅拷贝
        m_data = rep.m_data;
    }
    //赋值重载
    string_rep&operator=(const string_rep &rep)
    {
    
    
        if (this != &rep)
        {
    
    
            m_data = rep.m_data;
        }
        return *this;
    }
    //析构
    ~string_rep()
    {
    
    
        delete []m_data;
        m_data = nullptr;
    }

public:
    //计数器+1
    void increment()
    {
    
    
        m_count++;
    }
    //计数器-1
    void decrement()
    {
    
    
        m_count--;
        if (m_count == 0)
        {
    
    
            delete this;
        }
    }
    char* GetData()const
    {
    
    
        return m_data;
    }

private:
    char* m_data;
    int m_count;
};

class String
{
    
    
public:
    explicit String (const char *str=""):pn(new string_rep(str))
    {
    
    
        pn ->increment();
    }
    String(const String &s):pn(s.pn)
    {
    
    
        pn ->increment();
    }
    String&operator=(const String &s)
    {
    
    
        if (this != &s)
        {
    
    
            //这里先对计数器减1的操作是因为当你进行赋值的时候,改变了pn的指向,其原来的计数器m_count必须-1;
            pn ->decrement();
            pn = s.pn;
            pn ->increment();
        }
        return *this;
    }
    ~String()
    {
    
    
        pn ->decrement();
    }

public:
    //写时拷贝(转换大小写)
    void to_upper()
    {
    
    
        auto *new_pn = new string_rep(pn ->m_data);
        pn ->decrement();
        pn = new_pn;
        pn ->increment();

        char *p = pn ->m_data;
        while (*p != '\0')
        {
    
    
            if (*p >= 'a' && *p <= 'z')
                *p -= 32;
            p++;
        }
    }
private:
    string_rep *pn;
};

Guess you like

Origin blog.csdn.net/xhuyang111/article/details/115233342