Chinaunix首页 | 论坛 | 博客
  • 博客访问: 265782
  • 博文数量: 28
  • 博客积分: 3065
  • 博客等级: 中校
  • 技术积分: 610
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-30 15:30
文章分类

全部博文(28)

文章存档

2011年(3)

2009年(9)

2008年(16)

我的朋友

分类: C/C++

2009-07-07 21:20:46

简单的实现了下智能指针:

#include <iostream>
using namespace std;

template <class T>
class smart_ptr
{
    private:
        T *ptr;
        int *count;
        void free()
        {
            if (--(*count) == 0)
            {
                delete ptr;
            }
        }
    public:
        smart_ptr(T *p) : ptr(p), count(new int(1)){}
        smart_ptr(const smart_ptr &sp) : ptr(sp.ptr), count(sp.count)
        {
            ++(*count);
        }
        smart_ptr& operator=(const smart_ptr &sp)
        {
            free();
            count = sp.count;
            ptr = sp.ptr;
            ++(*count);
        }
        T* operator->()
        {
            if (*count == 0)
                return NULL;
            return ptr;
        }
        T& operator*()
        {
            if (*count == 0)
            {
                throw exception();
            }
            return *ptr;
        }
        ~smart_ptr()
        {
            free();
        }
};

struct A
{
        void f()
        {
            cout << "In A::f()" << endl;
        }
};

void test()
{
    smart_ptr<int> sptr1(new int(5));
    smart_ptr<int> sptr2(sptr1);
    cout << "*sptr1=" << *sptr1 << ",sptr2=" << *sptr2 << endl;
    smart_ptr<int> sptr3(new int(7));
    sptr2 = sptr3;
    cout << "*sptr1=" << *sptr1 << ",sptr2=" << *sptr2 << ",sptr3=" << *sptr3 << endl;

    smart_ptr<A> sptr4(new A());
    sptr4->f();
    (*sptr4).f();
}


int main(int argc, char *argv[])
{
    test();
    return 0;
}

阅读(493) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~