理解scope_ptr的内部实现

今天我们来谈论scope_ptr(局部智能指针),我们将与auto进行区别式进行阐述:

1.scope_ptr和auto_ptr类似,能够非常方便正确的删除创建的的对象。

2.scope_ptr在获取对象所指空间的控制权后,是不能将本空间的控制权在交由他人管理。这是与auto_ptr的区别。

3.scope_ptr在操作上面,不能实现拷贝构造、=(赋值)、判断相等或者不等(我们在这里实现这些,采用将这些函数写在类的私有属性中)。

4.最后我们在详谈当中的reset函数和swap函数:

typedef scope_ptr<int> this_type;
void
reset(T *p=0) { assert(p != 0 && p != px); this_type(p).swap(*this); } void swap(scope_ptr &b) { T *tmp = b.px; b.px = px; px = tmp; }

reset函数操作流程图如下:

1.this_type是我们宏定义的一种类类型;this_type(p).swap(*this),传入参数p调用构造函数创建无名临时对象来调用swap函数;注意:无名临时对象出了作用于会自动释放所指向的空间,所以不会造成内存泄漏。

2.在调用swap函数后,this指针的指向会发生变化。注意图二

3.swap函数执行指针交换指向的操作。

扫描二维码关注公众号,回复: 5360480 查看本文章

scope_ptr实现代码如下:

template<class T>
class scope_ptr
{
private:
    scope_ptr(scope_ptr const &);
    scope_ptr &operator=(scope_ptr const &);
    void operator==(scope_ptr const &)const;
    void operator!=(scope_ptr const &)const;
public:
    explicit scope_ptr(T *p = 0) :px(p) {} //构造函数
    ~scope_ptr()
    {
        delete px;
    }
public:
    void reset(T *p=0)
    {
        assert(p != 0 && p != px);
        this_type(p).swap(*this);
    }
    void swap(scope_ptr &b)
    {
        T *tmp = b.px;
        b.px = px;
        px = tmp;
    }
    T * operator->()const
    {
        assert(px != 0);
        return px;
    }
    T & operator*()const
    {
        assert(px != 0);
            return *px;
    }
private:
    T *px;
};
int main()
{
    int *p = new int(10);
    scope_ptr<int> pa(p);
    cout << *pa << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/single-dont/p/10431475.html
今日推荐