Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Chapter 12.  Optimization


12.4. Empty Derived Optimization

So EBO is about empty bases. What about empty child classes? Consider the following:



class X


{


  int i;


};





template <typename T>


class Y


  : T


{};





std::cout << sizeof(Y<X>); // What is the size of Y<X>?



Since Y does not provide any more member variables, and does not introduce any virtual members, to its parameterizing type, we'd ideally like to see it adding no additional memory requirements. Hence, sizeof(Y<X>) should equal sizeof(X). We could call this Empty Derived Optimization to mirror its more widely recognized older brother. So the question is, how do our compilers handle EDO?

As with EBO, there are several situations in which an empty child class can appear, as shown in Figures 12.3 and 12.4. Again P is the parent and C is the child. Note, however, that the use of template child classes is also evaluated, denoted by the angle braces.

Figure 12.3. Single inheritance EDO relationships.


Figure 12.4. Multiple-inheritance EDO relationships.


But why should we care about this? Well, as we'll see in several examples in Part Four, the use of template classes that derive from their parameterizing types is the basis of some powerful techniques. When we're using such techniques we would never want to waste space, and occasionally being a different size can render a technique invalid (see Chapter 21).

So how do our compilers go with this optimization? Table 12.4 shows that they do a fair bit better. In fact, only Borland has any problem with this optimization.[4] It does not support forms 5–8. However, when using the –Ve and –Vl flags together it does support forms 7 and 8.

[4] By the time you read this, the new Borland C++ compiler for C++BuilderX may be available, and we can hope it will fall into step with the others.

Table 12.4.

Compiler

EDO-1

EDO-2

EDO-3

EDO-4

EDO-5

EDO-6

EDO-7

EDO-8

Borland (5.6)

#

#

#

#

  

–Ve –Vl

–Ve –Vl

CodeWarrior

#

#

#

#

#

#

#

#

Comeau

#

#

#

#

#

#

#

#

Digital Mars

#

#

#

#

#

#

#

#

GCC

#

#

#

#

#

#

#

#

Intel

#

#

#

#

#

#

#

#

Visual C++

#

#

#

#

#

#

#

#

Watcom

#

#

#

#

#

#

#

#


So once again, if you wish to have efficient use of this facility, you have to select your compiler.


      Previous section   Next section