Chinaunix首页 | 论坛 | 博客
  • 博客访问: 86432
  • 博文数量: 21
  • 博客积分: 547
  • 博客等级: 中士
  • 技术积分: 217
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-22 09:41
文章分类

全部博文(21)

文章存档

2013年(3)

2012年(2)

2011年(10)

2010年(6)

分类: C/C++

2012-05-17 15:06:45

Sometimes easy things are easy, but they're still subtle. For example, suppose you have a class Widget, and you'd like to have a way to find out at run time how many Widget objects exist. An approach that's both easy to implement and that gives the right answer is to create a static counter in Widget, increment the counter each time a Widget constructor is called, and decrement it whenever the Widget destructor is called. You also need a static member function howMany to report how many Widgets currently exist. If Widget did nothing but track how many of its type exist, it would look more or less like this:

  1. class Widget {
  2. public:
  3.     Widget() { count; }
  4.     Widget(const Widget&) { count; }
  5.     ~Widget() { --count; }

  6.     static size_t howMany()
  7.     { return count; }

  8. private:
  9.     static size_t count;
  10. };

  11. // obligatory definition of count. This
  12. // goes in an implementation file
  13. size_t Widget::count = 0;

This works fine. The only mildly tricky thing is to remember to implement the copy constructor, because a compiler-generated copy constructor for Widget wouldn't know to increment count.

If you had to do this only for Widget, you'd be done, but counting objects is something you might want to implement for several classes. Doing the same thing over and over gets tedious, and tedium leads to errors. To forestall such tedium, it would be best to somehow package the above object-counting code so it could be reused in any class that wanted it. The ideal package would:

  • be easy to use — require minimal work on the part of class authors who want to use it. Ideally, they shouldn't have to do more than one thing, that is, more than basically say "I want to count the objects of this type."
  • be efficient — impose no unnecessary space or time penalties on client classes employing the package.
  • be foolproof — be next to impossible to accidently yield a count that is incorrect. (We're not going to worry about malicious clients, ones who deliberately try to mess up the count. In C , such clients can always find a way to do their dirty deeds.)

Stop for a moment and think about how you'd implement a reusable object-counting package that satisfies the goals above. It's probably harder than you expect. If it were as easy as it seems like it should be, you wouldn't be reading an article about it in this magazine.

new, delete, and Exceptions

While you're mulling over your solution to the object-counting problem, allow me to switch to what seems like an unrelated topic. That topic is the relationship between new and delete when constructors throw exceptions. When you ask C to dynamically allocate an object, you use a new expression, as in:

  1. class ABCD { ... }; // ABCD = "A Big Complex Datatype"
  2. ABCD *p = new ABCD; // a new expression

The new expression — whose meaning is built into the language and whose behavior you cannot change — does two things. First, it calls a memory allocation function called operator new. That function is responsible for finding enough memory to hold an ABCD object. If the call to operator new succeeds, the new expression then invokes an ABCD constructor on the memory that operator new found.

But suppose operator new throws a std::bad_alloc exception. Exceptions of this type indicate that an attempt to dynamically allocate memory has failed. In the new expression above, there are two functions that might give rise to that exception. The first is the invocation of operator new that is supposed to find enough memory to hold an ABCD object. The second is the subsequent invocation of the ABCD constructor that is supposed to turn the raw memory into a valid ABCD object.

If the exception came from the call to operator new, no memory was allocated. However, if the call to operator new succeeded and the invocation of the ABCD constructor led to the exception, it is important that the memory allocated by operator new be deallocated. If it's not, the program has a memory leak. It's not possible for the client — the code requesting creation of the ABCD object — to determine which function gave rise to the exception.

For many years this was a hole in the draft C language specification, but in March 1995 the C Standards committee adopted the rule that if, during a new expression, the invocation of operator new succeeds and the subsequent constructor call throws an exception, the runtime system must automatically deallocate the memory that operator new allocated. This deallocation is performed by operator delete, the deallocation analogue of operator new. (For details, see the sidebar on placement new and placement delete.)

It is this relationship between new expressions and operator delete affects us in our attempt to automate the counting of object instantiations.

Counting Objects

In all likelihood, your solution to the object-counting problem involved the development of an object-counting class. Your class probably looks remarkably like, perhaps even exactly like, the Widget class I showed earlier:


  1. // see below for a discussion of why
  2. // this isn't quite right

  3. class Counter {
  4. public:
  5.     Counter() { count; }
  6.     Counter(const Counter&) { count; }
  7.     ~Counter() { --count; }
  8.     static size_t howMany()
  9.         { return count; }

  10. private:
  11.     static size_t count;
  12. };
  13. // This still goes in an
  14. // implementation file
  15. size_t Counter::count = 0;

The idea here is that authors of classes that need to count the number of objects in existence simply use Counter to take care of the bookkeeping. There are two obvious ways to do this. One way is to define a Counter object as a class data member, as in:


  1. // embed a Counter to count objects
  2. class Widget {
  3. public:
  4.     ..... // all the usual public
  5.            // Widget stuff
  6.     static size_t howMany()
  7.     { return Counter::howMany(); }
  8. private:
  9.     ..... // all the usual private
  10.            // Widget stuff
  11.     Counter c;
  12. };

The other way is to declare Counter as a base class, as in:


  1. // inherit from Counter to count objects
  2. class Widget: public Counter {
  3.     ..... // all the usual public
  4.            // Widget stuff
  5. private:
  6.     ..... // all the usual private
  7.            // Widget stuff
  8. };

Both approaches have advantages and disadvantages. But before we examine them, we need to observe that neither approach will work in its current form. The problem has to do with the static object count inside Counter. There's only one such object, but we need one for each class using Counter. For example, if we want to count both Widgets and ABCDs, we need two static size_t objects, not one. Making Counter::count nonstatic doesn't solve the problem, because we need one counter per class, not one counter per object.

We can get the behavior we want by employing one of the best-known but oddest-named tricks in all of C : we turn Counter into a template, and each class using Counter instantiates the template with itself as the template argument.

Let me say that again. Counter becomes a template:


  1. template<typename T>
  2. class Counter {
  3. public:
  4.     Counter() { count; }
  5.     Counter(const Counter&) { count; }
  6.     ~Counter() { --count; }

  7.     static size_t howMany()
  8.     { return count; }

  9. private:
  10.     static size_t count;
  11. };

  12. template<typename T>
  13. size_t
  14. Counter<T>::count = 0; // this now can go in header
  15. The first Widget implementation choice now looks like:
  16. // embed a Counter to count objects
  17. class Widget {
  18. public:
  19.     .....
  20.     static size_t howMany()
  21.     {return Counter<Widget>::howMany();}
  22. private:
  23.     .....
  24.     Counter<Widget> c;
  25. };

And the second choice now looks like:


  1. // inherit from Counter to count objects
  2. class Widget: public Counter<Widget> {
  3.     .....
  4. };

Notice how in both cases we replace Counter with Counter. As I said earlier, each class using Counter instantiates the template with itself as the argument.

The tactic of a class instantiating a template for its own use by passing itself as the template argument was first publicized by Jim Coplien. He showed that it's used in many languages (not just C ) and he called it "a curiously recurring template pattern" . I don't think Jim intended it, but his description of the pattern has pretty much become its name. That's too bad, because pattern names are important, and this one fails to convey information about what it does or how it's used.

The naming of patterns is as much art as anything else, and I'm not very good at it, but I'd probably call this pattern something like "Do It For Me." Basically, each class generated from Counter provides a service (it counts how many objects exist) for the class requesting the Counter instantiation. So the class Counter counts Widgets, and the class Counter counts ABCDs.

Now that Counter is a template, both the embedding design and the inheritance design will work, so we're in a position to evaluate their comparative strengths and weaknesses. One of our design criteria was that object-counting functionality should be easy for clients to obtain, and the code above makes clear that the inheritance-based design is easier than the embedding-based design. That's because the former requires only the mentioning of Counter as a base class, whereas the latter requires that a Counter data member be defined and that howMany be reimplemented by clients to invoke Counter's howMany . That's not a lot of additional work (client howManys are simple inline functions), but having to do one thing is easier than having to do two. So let's first turn our attention to the design employing inheritance.

Using Public Inheritance

The design based on inheritance works because C guarantees that each time a derived class object is constructed or destroyed, its base class part will also be constructed first and destroyed last. Making Counter a base class thus ensures that a Counter constructor or destructor will be called each time a class inheriting from it has an object created or destroyed.

Any time the subject of base classes comes up, however, so does the subject of virtual destructors. Should Counter have one? Well-established principles of object-oriented design for C dictate that it should. If it has no virtual destructor, deletion of a derived class object via a base class pointer yields undefined (and typically undesirable) results:

  1. class Widget: public Counter<Widget>
  2. { ... };
  3. Counter<Widget> *pw =
  4.     new Widget; // get base class ptr
  5.                  // to derived class object
  6. ......
  7. delete pw; // yields undefined results
  8.            // if the base class lacks
  9.            // a virtual destructor

Such behavior would violate our criterion that our object-counting design be essentially foolproof, because there's nothing unreasonable about the code above. That's a powerful argument for giving Counter a virtual destructor.

Another criterion, however, was maximal efficiency (imposition of no unnecessary speed or space penalty for counting objects), and now we're in trouble. We're in trouble because the presence of a virtual destructor (or any virtual function) in Counter means each object of type Counter (or a class derived from Counter) will contain a (hidden) virtual pointer, and this will increase the size of such objects if they don't already support virtual functions . That is, if Widget itself contains no virtual functions, objects of type Widget would increase in size if Widget started inheriting from Counter. We don't want that.

The only way to avoid it is to find a way to prevent clients from deleting derived class objects via base class pointers. It seems that a reasonable way to achieve this is to declare operator delete private in Counter:

  1. template<typename T>
  2. class Counter {
  3. public:
  4.     .....
  5. private:
  6.     void operator delete(void*);
  7.     .....
  8. };

Now the delete expression won't compile:

  1. class Widget: public Counter<Widget> { ... };
  2. Counter<Widget> *pw = new Widget; ......
  3. delete pw; // Error. Can't call private
  4. // operator delete
  5. Unfortunately — and this is the really interesting part — the new expression shouldn't compile
  6. Counter<Widget> *pw =
  7.     new Widget; // this should not
  8.                  // compile because
  9.                  // operator delete is
  10.                  // private

Remember from my earlier discussion of new, delete, and exceptions that C 's runtime system is responsible for deallocating memory allocated by operator new if the subsequent constructor invocation fails. Recall also that operator delete is the function called to perform the deallocation. But we've declared operator delete private in Counter, which makes it invalid to create objects on the heap via new!

Yes, this is counterintuitive, and don't be surprised if your compilers don't yet support this rule, but the behavior I've described is correct. Furthermore, there's no other obvious way to prevent deletion of derived class objects via Counter* pointers, and we've already rejected the notion of a virtual destructor in Counter. So I say we abandon this design and turn our attention to using a Counter data member instead.

Using a Data Member

We've already seen that the design based on a Counter data member has one drawback: clients must both define a Counter data member and write an inline version of howMany that calls the Counter's howMany function. That's marginally more work than we'd like to impose on clients, but it's hardly unmanageable. There is another drawback, however. The addition of a Counter data member to a class will often increase the size of objects of that class type.

At first blush, this is hardly a revelation. After all, how surprising is it that adding a data member to a class makes objects of that type bigger? But blush again. Look at the definition of Counter:

  1. template<typename T>
  2. class Counter {
  3. public:
  4.     Counter();
  5.     Counter(const Counter&);
  6.     ~Counter();

  7.     static size_t howMany();
  8. private:
  9.     static size_t count;
  10. };

Notice how it has no nonstatic data members. That means each object of type Counter contains nothing. Might we hope that objects of type Counter have size zero? We might, but it would do us no good. C is quite clear on this point. All objects have a size of at least one byte, even objects with no nonstatic data members. By definition, sizeof will yield some positive number for each class instantiated from the Counter template. So each client class containing a Counter object will contain more data than it would if it didn't contain the Counter.

(Interestingly, this does not imply that the size of a class without a Counter will necessarily be bigger than the size of the same class containing a Counter. That's because alignment restrictions can enter into the matter. For example, if Widget is a class containing two bytes of data but that's required to be four-byte aligned, each object of type Widget will contain two bytes of padding, and sizeof(Widget) will return 4. If, as is common, compilers satisfy the requirement that no objects have zero size by inserting a char into Counter, it's likely that sizeof(Widget) will still yield 4 even if Widget contains a Counter object. That object will simply take the place of one of the bytes of padding that Widget already contained. This is not a terribly common scenario, however, and we certainly can't plan on it when designing a way to package object-counting capabilities.)

I'm writing this at the very beginning of the Christmas season. (It is in fact Thanksgiving Day, which gives you some idea of how I celebrate major holidays...) Already I'm in a Bah Humbug mood. All I want to do is count objects, and I don't want to haul along any extra baggage to do it. There has got to be a way.

Using Private Inheritance

Look again at the inheritance-based code that led to the need to consider a virtual destructor in Counter:


  1. class Widget: public Counter<Widget>
  2. { ... };
  3. Counter<Widget> *pw = new Widget;
  4. ......
  5. delete
  6. pw; // yields undefined results
  7.      // if Counter lacks a virtual
  8.      // destructor

Earlier we tried to prevent this sequence of operations by preventing the delete expression from compiling, but we discovered that that also prohibited the new expression from compiling. But there is something else we can prohibit. We can prohibit the implicit conversion from a Widget* pointer (which is what new returns) to a Counter* pointer. In other words, we can prevent inheritance-based pointer conversions. All we have to do is replace the use of public inheritance with private inheritance:

  1. class Widget: private Counter<Widget>
  2. { ... };
  3. Counter<Widget> *pw =
  4.     new Widget; // no implicit
  5.                  // conversion from
  6.                  // Widget* to
  7.                  // Counter<Widget>*

Furthermore, we're likely to find that the use of Counter as a base class does not increase the size of Widget compared to Widget's stand-alone size. Yes, I know I just finished telling you that no class has zero size, but — well, that's not really what I said. What I said was that no objects have zero size. The C Standard makes clear that the base-class part of a more derived object may have zero size. In fact many compilers implement what has come to be known as the empty base optimization .

Thus, if a Widget contains a Counter, the size of the Widget must increase. The Counter data member is an object in its own right, hence it must have nonzero size. But if Widget inherits from Counter, compilers are allowed to keep Widget the same size it was before. This suggests an interesting rule of thumb for designs where space is tight and empty classes are involved: prefer private inheritance to containment when both will do.

This last design is nearly perfect. It fulfills the efficiency criterion, provided your compilers implement the empty base optimization, because inheriting from Counter adds no per-object data to the inheriting class, and all Counter member functions are inline. It fulfills the foolproof criterion, because count manipulations are handled automatically by Counter member functions, those functions are automatically called by C , and the use of private inheritance prevents implicit conversions that would allow derived-class objects to be manipulated as if they were base-class objects. (Okay, it's not totally foolproof: Widget's author might foolishly instantiate Counter with a type other than Widget, i.e., Widget could be made to inherit from Counter. I choose to ignore this possibility.)

The design is certainly easy for clients to use, but some may grumble that it could be easier. The use of private inheritance means that howMany will become private in inheriting classes, so such classes must include a using declaration to make howMany public to their clients:

  1. class Widget: private Counter<Widget> {
  2. public:
  3.     // make howMany public
  4.     using Counter<Widget>::howMany;

  5.     ..... // rest of Widget is unchanged
  6. };

  7. class ABCD: private Counter<ABCD> {
  8. public:
  9.     // make howMany public
  10.     using Counter<ABCD>::howMany;

  11.     ..... // rest of ABCD is unchanged
  12. };
Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.5pt; mso-bidi-font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-font-kerning:1.0pt;}

For compilers not supporting namespaces, the same thing is accomplished by replacing the using declaration with the older (now deprecated) access declaration:

  1. class Widget: private Counter<Widget> {
  2. public:
  3.     // make howMany public
  4.     Counter<Widget>::howMany;

  5.     ..... // rest of Widget is unchanged
  6. };
Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt
阅读(866) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~