zoukankan      html  css  js  c++  java
  • C++优化string,实现写时拷贝

    /*
    优化string
    复制的时候 仅复制引用,只有在修改内容时,才复制内容
    即实现写时拷贝
    */
    
    class COWMyString
    {
    public:
        //默认参数
        COWMyString(const char *str = "") :m_str(strcpy(new char[strlen(str) + 1], str))
        {
            if (m_str) {
                m_count = new size_t(1);
            }
            else {
                m_count = new size_t(0);
            }
        }
    
        ~COWMyString(void)
        {
    
            (*this->m_count)--;
            if (*this->m_count == 0)
            {
                delete []this->m_str;
                delete this->m_count;
            }
        }
    
        //深拷贝构造
        COWMyString(const COWMyString&that)
        {
            if (this != &that) {
                this->m_str = that.m_str;
                //指针指向的实际上是同一个计数器,同一块内存
                this->m_count = that.m_count;
                (*this->m_count)++;
            }
        }
    
        //深拷贝赋值
        COWMyString&operator=(const COWMyString&that)
        {
            //指针指向的实际上是同一个计数器,同一块内存
            if (this->m_str == that.m_str)
            {
                return *this;
            }
    
            if (this->m_str)
            {
                //将原来的引用计数减一
                (*this->m_count)--;
                if (this->m_count == 0) {
                    delete []this->m_str;
                    delete this->m_count;
                }
    
                this->m_str = that.m_str;
                //指针指向的实际上是同一个计数器,同一块内存
                this->m_count = that.m_count;
                (*this->m_count)++;
            }
    
            return *this;
        }
    
        //copy on write
        char &operator[](size_t index)
        {
            if (index>strlen(m_str))
            {
                static char nullchar = 0;
                return nullchar;
            }
            (*this->m_count)--;
            m_str = strcpy(new char[strlen(m_str)+1], m_str);
            m_count = new size_t(1);
    
            return *(m_str + index);
    
        }
    
        const char *c_str(void)const
        {
            return m_str;
        }
    
    private:
        //指针
        char* m_str;
        //计数器
        size_t* m_count;
    };
  • 相关阅读:
    200. Number of Islands
    [Leetcode] 70. Climbing Stairs Java
    LeetCode 64. Minimum Path Sum Java
    LeetCode 63. Unique Paths II Java
    LeetCode 62. Unique Paths Java
    [LeetCode 241] Different Ways to Add Parentheses Java
    LeetCode 240. Search a 2D Matrix II Java
    LeetCode 215. Kth Largest Element in an Array Java
    LeetCode 169. Majority Element Java
    LeetCode 53. Maximum Subarray Java
  • 原文地址:https://www.cnblogs.com/LuckCoder/p/14550435.html
Copyright © 2011-2022 走看看