zoukankan      html  css  js  c++  java
  • careercup-C和C++ 13.8

    13.8 编写一个智能指针类。智能指针是一种数据类型,一般用模板实现,模拟指针行为的同时还提供自动垃圾回收机制。它会自动记录SmartPointer<T*>对象的引用计数,一旦T类型对象的引用计数为零,就会释放该对象。

    解法:

    智能指针跟普通指针一样,但他借助自动化内存管理保证了安全性,避免了诸如悬挂指针、内存泄漏和分配失败等问题。

    智能指针必须为给定对象的所有引用维护单一引用计数。主要实现构造函数、复制构造函数和赋值运算符,析构函数。

    C++实现代码:

    #include<iostream>
    #include<cstdlib>
    #include<new>
    using namespace std;
    
    template <typename T>
    class SmartPointer
    {
    public:
        SmartPointer(T* ptr)
        {
            ref=ptr;
            ref_count=(unsigned*)malloc(sizeof(unsigned));
            *ref=1;
        }
        SmartPointer(SmartPointer<T> &sptr)
        {
            ref=sptr.ref;
            ref_count=sptr.ref_count;
            ++(*ref_count);
        }
        SmartPointer<T> &operator=(SmartPointer<T> &sptr)
        {
            if(this==&sptr) return *this;
            if(*ref_count>0)
            {
                remove();
            }
            ref=sptr.ref;
            ref_count=sptr.ref_count;
            ++(*ref_count);
            return *this;
        }
        ~SmartPointer()
        {
            remove();
        }
    
        T getValue()
        {
            return *ref;
        }
    protected:
        void remove()
        {
            --(*ref_count);
            if(*ref_count==0)
            {
                delete ref;
                free(ref_count);
                ref=NULL;
                ref_count=NULL;
            }
        }
    private:
        T* ref;
        unsigned *ref_count;
    };
    
    int main()
    {
        int *p1=new int();
        *p1=1111;
        int *p2=new int();
        *p2=22222;
        SmartPointer<int> sp1(p1),sp2(p2);
        SmartPointer<int> spa=sp1;
        sp2=spa;
    }
  • 相关阅读:
    python10.31
    python10.29
    python10.28
    python10.27
    python10.25
    python10.24
    python10.23
    四边形不等式与决策单调
    0x57~0x59
    0x55~0x56
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4157368.html
Copyright © 2011-2022 走看看