Re: Reducing the virtual function table size...
In article <1176833857.521036.138870@y5g2000hsa.googlegroups.com>,
peter koch <peter.koch.larsen@gmail.com> wrote:
On 17 Apr., 03:40, "Chris Thomasson" <cris...@comcast.net> wrote:
Consider an an object that that can has 7 or 8 functions. If you create an
abstract base class for the "interface" of the object, well, that means 7 or
8 pure virtual functions right?
I dont see why. As others have explained, the vtable is a per class
entity: the instance just has a pointer to the vtable.
Well, IMHO, that's way too much... I was
wondering if the following technique is "frowned" upon:
Not at all. Actually, I'd often prefer virtual to be private.
<pseudo-code>
_____________
typedef struct ... vztimespec_t;
class condmutex_base {
public:
enum wait_e {
WAITLOCK, TRYLOCK, WAITCOND
};
enum wake_e {
UNLOCK, SIGNAL, BROADCAST
};
protected:
condmutex_base() {}
public:
virtual ~condmutex_base() {}
private:
virtual bool wait(wait_e, vztimespec_t const*) = 0;
virtual bool wake(wake_e) = 0;
public:
inline void unlock() { wake(wake_e::UNLOCK); }
inline void waitlock() { wait(wait_e::WAITLOCK, 0); }
inline void waitcond() { wait(wait_e::WAITCOND, 0); }
inline bool trylock() { return wait(wait_e::TRYLOCK, 0); }
inline bool signal() { return wake(wake_e::SIGNAL); }
inline bool broadcast() { return wake(wake_e::BROADCAST); }
inline bool timedwaitcond(vztimespec_t const *tspec) {
return wait(wait_e::WAITCOND, tspec);
}};
_____________
I only have 2 virtual functions now, not counting dtor, ect... Well, 2 is
better than 7, or 8?
It is better in the sense, that in reality only two virtual functions
are needed. The extra storage cost of the extra virtual functions
should not matter in anything but the most extreme cases.
Yes, you do save a few pointers in the vtable, but now each implementation
of wait() and wake() has to separate out the different cases at runtime,
which will likely be done with a big switch() which is implemented by a
jump table, so you are back to the same or greater cost, plus additional
run-time overhead.
Where this might be a win, though, is if there is a significant amount of
common code in wait() and wake() for all cases. Then in this implementation,
that code would exist only once, but would be replicated in each of the
other cases (or more likely pulled out into a common subroutine or two).
Now, consider if you have a derived class that wants to change the behavior
of the signal() method. In this case, the entire wake() method would
have to be re-implemented. With individual functions, only signal()
would need re-implementation. Obviously you expect derived classes,
otherwise what is the point in having virtual functions at all??
--
Marcus Hall
marcus@tuells.org