勤能补拙,厚积薄发

合抱之木,生于毫末;九层之台,起于垒土;千里之行,始于足下
随笔 - 19, 文章 - 0, 评论 - 3, 引用 - 0
数据加载中……

More Effective C++(item26)

restrict the object number of a class
 1#include <iostream>
 2
 3using namespace std;
 4
 5template <class BeingCounted>
 6class Counted {
 7    public:
 8        class TooManyObjects{};// the exception class
 9        static int objectCount() return numObjects; }
10    protected:
11        Counted();
12        Counted(const Counted& rhs);
13        ~Counted()--numObjects;}
14    private:
15        static int numObjects;
16        static const size_t maxObjects;
17        void init();        // avoid ctor repeat codes
18}
;
19
20template <class BeingCounted>
21Counted<BeingCounted>::Counted()
22{
23    init();
24}

25
26template <class BeingCounted>
27Counted<BeingCounted>::Counted(const Counted<BeingCounted>&)
28{
29    init();
30}

31
32template <class BeingCounted>
33void Counted<BeingCounted>::init()
34{
35    if (numObjects >= maxObjects) {
36        throw TooManyObjects();
37    }

38    ++numObjects;
39}

40class PrintJob;
41class Printer: private Counted<Printer> {
42    public:
43        // pseudo-constructors
44        static Printer* makePrinter();
45        static Printer* makePrinter(const Printer& rhs);
46        ~Printer();
47        void submitJob(const PrintJob& job);
48        void reset();
49        void performSelfTest();
50        // 
51        using Counted<Printer>::objectCount;
52        using Counted<Printer>::TooManyObjects;
53    private:
54        Printer();
55        Printer(const Printer& rhs);
56}
;
57
58template <class Printer>
59int Counted<Printer>::numObjects = 0;
60
61template <class Printer> 
62const size_t Counted<Printer>::maxObjects = 10;
63
在gcc4.4.1下编译通过

posted on 2011-12-13 13:50 lee007 阅读(369) 评论(0)  编辑 收藏 引用 所属分类: Programming Study


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理