实现类似shared_ptr的引用计数

简介: 13.27 定义使用引用计数版本的HasPtr #include #include #include using namespace std; class HasPtr { public: HasPtr(const string &s=string()):ps(new...

13.27 定义使用引用计数版本的HasPtr

#include<iostream>
#include<string>
#include<new>

using namespace std;
class HasPtr
{
public:
    HasPtr(const string &s=string()):ps(new string(s)),i(0),use(new size_t(1)) {cout<<"constructer"<<endl;}
    HasPtr(const HasPtr &h):i(h.i)
    {
        cout<<"copy constructer"<<endl;
        ps=h.ps;
        ++*h.use;
        use=h.use;
    }
    HasPtr& operator=(const HasPtr &h)
    {
        ++*h.use;
        //将原来分配的内存空间删除
        while(--*use==0)
        {
            delete ps;
            delete use;
        }
        //指向新的内存空间
        ps=h.ps;
        i=h.i;
        use=h.use;
        return *this;
    }
    //如果在赋值操作中删除了左边对象的内存空间,则此处调用析构函数时将不再删除内存空间,但是该对象还是会被析构
    ~HasPtr()
    {
        if(--*use==0)
        {
            delete ps;
            delete use;
        }
        cout<<"destructer"<<endl;
    }
private:
    string *ps;
    int i;
    size_t *use;
};
int main()
{
    HasPtr h;
    HasPtr hh(h);
    hh=h;
    return 0;
}

 

相关文章
shared_ptr能和基于引用计数的智能指针混用吗?
shared_ptr能和基于引用计数的智能指针混用吗?
|
3月前
|
C++
C++智能指针shared_ptr
C++智能指针shared_ptr
23 0
|
3月前
|
安全 编译器 C++
智能指针shared_ptr、unique_ptr、weak_ptr
智能指针shared_ptr、unique_ptr、weak_ptr
79 0
|
3月前
shared_ptr循环引用问题以及解决方法
shared_ptr循环引用问题以及解决方法
37 0
|
3月前
|
C++
C++智能指针weak_ptr
C++智能指针weak_ptr
15 0
|
4月前
|
安全 编译器 C++
[C++] 智能指针(shared_ptr、unique_ptr)
[C++] 智能指针(shared_ptr、unique_ptr)
27 1
|
4月前
C++11 shared_ptr智能指针
C++11 shared_ptr智能指针
30 0
shared_ptr产生的交叉引用问题
智能指针方便了程序设计人员对于内存的使用,但是也带来了很多问题。如交叉引用问题、线程安全问题等,本文将详细介绍交叉引用问题。
|
4月前
C++11 weak_ptr智能指针
C++11 weak_ptr智能指针
22 0
|
10月前
|
程序员 C++
C++11之智能指针(unique_ptr、shared_ptr、weak_ptr、auto_ptr)浅谈内存管理
C++11之智能指针(unique_ptr、shared_ptr、weak_ptr、auto_ptr)浅谈内存管理
85 0