修身养性,止于至善___leiming32的博客

一个简单的智能指针类_DogPtr句柄类

这个是我今天复习primer时仿写的一个句柄类,更容易理解一些.
 1#include <iostream>
 2using namespace std;
 3
 4class Dog {
 5public:
 6    virtual void run() const {   // 需要注意的是这里的const
 7        cout << "Dog run" << endl;
 8    }

 9    virtual Dog* clone() const // 执行此函数的是DogPtr构造函数中的const形参,所以要const
10        return (new Dog(*this));
11    }

12}
;
13class HotDog: public Dog {
14    void run()  const {
15        cout << "hotdog run" << endl;
16    }

17    HotDog* clone() const {
18        return (new HotDog(*this));
19    }

20}
;
21
22//句柄类,指针类 // 大家共同指向的是基础对象的副本 
23class DogPtr {
24public:
25    DogPtr(): p(0), use(new size_t(1)) {}
26    DogPtr(const Dog&d): p(d.clone()), use(new size_t(1)) {} // 使用clone函数
27
28    //复制控制
29    DogPtr(const DogPtr &d): p(d.p), use(d.use) ++*use; }
30    ~DogPtr()  { decr_use(); }
31    DogPtr& operator=(const DogPtr&);
32
33    //成员访问符*与->的重载
34    const Dog* operator->() const 
35        if (p)    return p;
36        else throw logic_error("operator->: p null");
37    }

38    const Dog& operator*() const {
39        if (p)    return *p;
40        else throw logic_error("operator*: p null");
41    }

42
43private:
44    Dog *p;
45    size_t *use; // 计数指针
46    void decr_use() {
47        if (--*use == 0{ delete p; delete use; }
48    }

49}
;
50
51DogPtr&
52DogPtr::operator =(const DogPtr &rhs) {
53    ++*rhs.use; // 前缀
54    decr_use();
55    p = rhs.p;
56    use = rhs.use;
57    return *this;
58}

59
60int main()
61{
62    Dog d;
63    HotDog hd;
64
65    DogPtr dp1(hd);
66    dp1->run();
67    
68
69    return 0;
70}

posted on 2010-10-20 20:50 狼在北方 阅读(179) 评论(0)  编辑 收藏 引用 所属分类: C++编程语言