zoukankan      html  css  js  c++  java
  • reference couting引用计数

    #include <stdio.h>
    #include <string.h>
    class String        
    {            
    private:            
        struct StringValue            
        {        
            int refCount;
            char *data;
            StringValue(const char *initValue);
            ~StringValue();
        };
        StringValue *value;
    public:
        String(const char *initValue = "");         //constructor
        String(const String &rhs);                  //copy constructor
        String &operator=(const String &rhs);       //assignment operator
        const char &operator[](size_t index) const; //重载[]运算符,针对const Strings
        char &operator[](size_t index);             //重载[]运算符,针对non-const Strings
        ~String();                                  //destructor
    };
    String::StringValue::StringValue(const char *initValue) : refCount(1)
    {
        data = new char[strlen(initValue) + 1];
        strcpy_s(data, 1, initValue);    
    }
    String::StringValue::~StringValue()
    {
        delete[] data;
    }    
    String::String(const char *initValue) : value(new StringValue(initValue))
    {                
    }
    String::String(const String &rhs) : value(rhs.value)            
    {        
        ++value->refCount;    
    }        
    String::~String()    
    {        
        if (--value->refCount == 0)        
            delete value;
    }    
    String &String::operator=(const String &rhs)
    {
        if (this->value == rhs.value) //自赋值
            return *this;
        //赋值时左操作数引用计数减1,当变为0时,没有指针指向该内存,销毁
        if (--value->refCount == 0)
            delete value;
        //不必开辟新内存空间,只要让指针指向同一块内存,并把该内存块的引用计数加1
        value = rhs.value;
        ++value->refCount;
        return *this;
    }
    const char &String::operator[](size_t index) const
    {    
        return value->data[index];
    }
    //重载[]运算符,针对non-const Strings
    char &String::operator[](size_t index)
    {    
        if (value->refCount > 1)    
        {    
            --value->refCount;
            value = new StringValue(value->data);
        }
        if (index < strlen(value->data))
            return value->data[index];
    }
    #include <iostream>
    #include <string>
    using namespace std;
    std::string a = "lvlv";
    void main()
    {            
        char *p = &a[1];            
        *p = 'a';    
        std::string b = a;
        std::cout << "b:" << b << endl;
        system("pause");    
        return;            
    }
  • 相关阅读:
    分布式事务的四种解决方案
    uber-go/guide 的中文翻译
    域名解析-CNAME
    Nginx节点存活状态检查
    Laravel核心解读--中间件(Middleware)
    Mac dyld: Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib
    前缀树算法实现路由匹配原理解析
    原创-实用salt部署文档(持续更新)
    线上案例-调参-设置滑动窗口提高视频云播放性能
    NGINX日志割切
  • 原文地址:https://www.cnblogs.com/feihum/p/11132352.html
Copyright © 2011-2022 走看看