首页 > 其他 > 详细

reference couting引用计数

时间:2019-07-04 15:03:18      阅读:105      评论:0      收藏:0      [点我收藏+]
#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;            
}

reference couting引用计数

原文:https://www.cnblogs.com/feihum/p/11132352.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!