引用计数

来源:互联网 发布:oracle数据库备份语句 编辑:程序博客网 时间:2024/05/20 04:15

C++中没有垃圾收集机制,但是C++提供了我们能够实现我们想要的一切的基础。

下面我简单了实现了一个引用技术的类,没有什么设计可言,只是演示一下。引用计数将客户需要做的销毁对象的代码迁移到对象本身,对象在不被使用时即计数为0时自身实现销毁。

/**************************************************author:周翔*e-mail:604487178@qq.com*blog:http://blog.csdn.net/zhx6044***************************************************/#ifndef OBJECT_H#define OBJECT_H#include <cstring>#include <iostream>class Object{public:    Object(const char* _value);    ~Object();    Object(const Object &v);    Object& operator =(const Object &v);    const char* getValue() const;private:    int *_ref_counter;//用来计数    char* m_value;};#endif // OBJECT_H/**************************************************author:周翔*e-mail:604487178@qq.com*blog:http://blog.csdn.net/zhx6044***************************************************/#include "object.h"Object::Object(const char *_value){    this->m_value = new char[strlen(_value) + 1];    strcpy(this->m_value,_value);    this->_ref_counter = new int;    *this->_ref_counter = 1;}Object::~Object(){    if (--(*this->_ref_counter) == 0) {        delete[] this->m_value;        delete this->_ref_counter;        std::cout << "delete";    }}Object::Object(const Object &v){    this->m_value = v.m_value;    this->_ref_counter = v._ref_counter;    ++(*this->_ref_counter);}Object& Object::operator =(const Object &v){    if (this == &v) return *this;    if (--(*this->_ref_counter) == 0) {        delete[] m_value;        delete this->_ref_counter;    }    this->m_value = v.m_value;    this->_ref_counter = v._ref_counter;    ++(*this->_ref_counter);    return *this;}const char* Object::getValue() const{    return this->m_value;}#include <iostream>#include "object.h"using namespace std;int main(){    Object obj("zhou xiang love cc");    cout << obj.getValue() << endl;    Object obj2 = obj;    cout << obj2.getValue() << endl;    Object obj3(obj2);    cout << obj3.getValue() << endl;    return 0;}


引用计数有力于减少内存消耗,它还与写时复制技术一起使用。
原创粉丝点击