⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mc5.htm

📁 一个非常适合初学者入门的有关c++的文档
💻 HTM
📖 第 1 页 / 共 5 页
字号:
CPFMachine m1;                               // fineCPFMachine m2;                               // throws TooManyObjects exceptionThe problem is that Printer objects can exist in three different contexts: on their own, as base class parts of more derived objects, and embedded inside larger objects. The presence of these different contexts significantly muddies the waters regarding what it means to keep track of the "number of objects in existence," because what you consider to be the existence of an object may not jibe with your compilers'.Often you will be interested only in allowing objects to exist on their own, and you will wish to limit the number of those kinds of instantiations. That restriction is easy to satisfy if you adopt the strategy exemplified by our original Printer class, because the Printer constructors are private, and (in the absence of friend declarations) classes with private constructors can't be used as base classes, nor can they be embedded inside other objects.The fact that you can't derive from classes with private constructors leads to a general scheme for preventing derivation, one that doesn't necessarily have to be coupled with limiting object instantiations. Suppose, for example, you have a class, FSA, for representing finite state automata. (Such state machines are useful in many contexts, among them user interface design.) Further suppose you'd like to allow any number of FSA objects to be created, but you'd also like to ensure that no class ever inherits from FSA. (One reason for doing this might be to justify the presence of a nonvirtual destructor in FSA. Item E14 explains why base classes generally need virtual destructors, and Item 24 explains why classes without virtual functions yield smaller objects than do equivalent classes with virtual functions.) Here's how you can design FSA to satisfy both criteria: class FSA {public:  // pseudo-constructors  static FSA * makeFSA();  static FSA * makeFSA(const FSA& rhs);  ...private:  FSA();  FSA(const FSA& rhs);  ...};FSA * FSA::makeFSA(){ return new FSA(); }FSA * FSA::makeFSA(const FSA& rhs){ return new FSA(rhs); }Unlike the thePrinter function that always returned a reference to a single object, each makeFSA pseudo-constructor returns a pointer to a unique object. That's what allows an unlimited number of FSA objects to be created.This is nice, but the fact that each pseudo-constructor calls new implies that callers will have to remember to call delete. Otherwise a resource leak will be introduced. Callers who wish to have delete called automatically when the current scope is exited can store the pointer returned from makeFSA in an auto_ptr object (see Item 9); such objects automatically delete what they point to when they themselves go out of scope: // indirectly call default FSA constructorauto_ptr<FSA> pfsa1(FSA::makeFSA());// indirectly call FSA copy constructorauto_ptr<FSA> pfsa2(FSA::makeFSA(*pfsa1));...                            // use pfsa1 and pfsa2 as normal pointers,                               // but don't worry about deleting themAllowing Objects to Come and GoWe now know how to design a class that allows only a single instantiation, we know that keeping track of the number of objects of a particular class is complicated by the fact that object constructors are called in three different contexts, and we know that we can eliminate the confusion surrounding object counts by making constructors private. It is worthwhile to make one final observation. Our use of the thePrinter function to encapsulate access to a single object limits the number of Printer objects to one, but it also limits us to a single Printer object for each run of the program. As a result, it's not possible to write code like this: create Printer object p1;use p1;destroy p1;create Printer object p2;use p2;destroy p2;...This design never instantiates more than a single Printer object at a time, but it does use different Printer objects in different parts of the program. It somehow seems unreasonable that this isn't allowed. After all, at no point do we violate the constraint that only one printer may exist. Isn't there a way to make this legal?There is. All we have to do is combine the object-counting code we used earlier with the pseudo-constructors we just saw: class Printer {public:  class TooManyObjects{};  // pseudo-constructor  static Printer * makePrinter();~Printer();  void submitJob(const PrintJob& job);  void reset();  void performSelfTest();  ...private:  static size_t numObjects;  Printer();  Printer(const Printer& rhs);           // we don't define this};                                       // function, because we'll                                         // never allow copying                                         // (see Item E27)// Obligatory definition of class staticsize_t Printer::numObjects = 0;Printer::Printer(){  if (numObjects >= 1) {    throw TooManyObjects();  }  proceed with normal object construction here;  ++numObjects;}Printer * Printer::makePrinter(){ return new Printer; }If the notion of throwing an exception when too many objects are requested strikes you as unreasonably harsh, you could have the pseudo-constructor return a null pointer instead. Clients would then have to check for this before doing anything with it, of course.Clients use this Printer class just as they would any other class, except they must call the pseudo-constructor function instead of the real constructor: Printer p1;                                  // error! default ctor is                                             // privatePrinter *p2 =  Printer::makePrinter();                    // fine, indirectly calls                                             // default ctorPrinter p3 = *p2;                            // error! copy ctor is                                             // privatep2->performSelfTest();                       // all other functions arep2->reset();                                 // called as usual...delete p2;                                   // avoid resource leak; this                                             // would be unnecessary if                                             // p2 were an auto_ptrThis technique is easily generalized to any number of objects. All we have to do is replace the hard-wired constant 1 with a class-specific value, then lift the restriction against copying objects. For example, the following revised implementation of our Printer class allows up to 10 Printer objects to exist: class Printer {public:  class TooManyObjects{};  // pseudo-constructors  static Printer * makePrinter();  static Printer * makePrinter(const Printer& rhs);  ...private:  static size_t numObjects;  static const size_t maxObjects = 10;       // see below  Printer();  Printer(const Printer& rhs);};// Obligatory definitions of class staticssize_t Printer::numObjects = 0;const size_t Printer::maxObjects;Printer::Printer(){  if (numObjects >= maxObjects) {    throw TooManyObjects();  }  ...}Printer::Printer(const Printer& rhs){  if (numObjects >= maxObjects) {    throw TooManyObjects();  }  ...}Printer * Printer::makePrinter(){ return new Printer; }Printer * Printer::makePrinter(const Printer& rhs){ return new Printer(rhs); }Don't be surprised if your compilers get all upset about the declaration of Printer::maxObjects in the class definition above. In particular, be prepared for them to complain about the specification of 10 as an initial value for that variable. The ability to specify initial values for static const members (of integral type, e.g., ints, chars, enums, etc.) inside a class definition was added to C++ only relatively recently, so some compilers don't yet allow it. If your compilers are as-yet-unupdated, pacify them by declaring maxObjects to be an enumerator inside a private anonymous enum, class Printer {private:  enum { maxObjects = 10 };                  // within this class,  ...                                        // maxObjects is the};                                           // constant 10or by initializing the constant static like a non-const static member: class Printer {private:  static const size_t maxObjects;            // no initial value given  ...};// this goes in a single implementation fileconst size_t Printer::maxObjects = 10;This latter approach has the same effect as the original code above, but explicitly specifying the initial value is easier for other programmers to understand. When your compilers support the specification of initial values for const static members in class definitions, you should take advantage of that capability.An Object-Counting Base ClassInitialization of statics aside, the approach above works like the proverbial charm, but there is one aspect of it that continues to nag. If we had a lot of classes like Printer whose instantiations needed to be limited, we'd have to write this same code over and over, once per class. That would be mind-numbingly dull. Given a fancy-pants language like C++, it somehow seems we should be able to automate the process. Isn't there a way to encapsulate the notion of counting instances and bundle it into a class?We can easily come up with a base class for counting object instances and have classes like Printer inherit from that, but it turns out we can do even better. We can actually come up with a way to encapsulate the whole counting kit and kaboodle, by which I mean not only the functions to manipulate the instance count, but also the instance count itself. (We'll see the need for a similar trick when we examine reference counting in Item 29. For a detailed examination of this design, see my article on counting objects.)The counter in the Printer class is the static variable numObjects, so we need to move that variable into an instance-counting class. However, we also need to make sure that each class for which we're counting instances has a separate counter. Use of a counting class template lets us automatically generate the appropriate number of counters, because we can make the counter a static member of the classes generated from the template: template<class BeingCounted>class Counted {public:  class TooManyObjects{};                     // for throwing exceptions  static int objectCount() { return numObjects; }protected:  Counted();  Counted(const Counted& rhs);  ~Counted() { --numObjects; }private:

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -