C++ : Are inline virtual destructors an optimization?

Started by
2 comments, last by random_thinker 18 years, 8 months ago
I just reviewed a web-site on Functionoids, which advised that inline destructors for virtual classes are faster. The code was something like this:

class Foo
{
   virtual ~Foo();
   virtual void Bar(int) = 0;
};

inline Foo::~Foo()
{ }
If so, why? And should all virtual destructors be inlined when speed is important? --random
--random_thinkerAs Albert Einstein said: 'Imagination is more important than knowledge'. Of course, he also said: 'If I had only known, I would have been a locksmith'.
Advertisement
Base class destructors are automatically called by the derived class destructors. In that sense virtual destructors are different than normal virtual functions. By inlining a virtual destructor a derived class will have access to the definition of the base class destructor and thus inline the base class destructor, which will eliminate the call overhead of calling the virtual destructor. As usual, I recommend only inlining if your profiler tells you there's a bottleneck or if it is necessary (like for template classes).
I suppose that the speed gain is very very very marginal and probaly, if your destructor does something, you have no benefit at all from inline it!
Thanks Si,

That's very interesting, and explains their advice excellently. I suppose that Functionoids, which can be used in place of function pointers in C++ (and are more powerful) would be called frequently (often within a loop) which would make this inline call worthwhile.

I've just used this concept to write a text parser (state machine) which works superbly, and is very easy to maintain. Using functionoids, it is possible to produce a completely encapsulated parser, that can be called in code like this:

void Database::parse( const string data_file, const string state_file ){   char ch;   ifstream in(data_file);   ofstream out(state_file);      FSMAction filter; // FSM machine functionoid, encapsulated and polymorphic w/ctor args.      while (in.get(ch))   {      filter(ch,out);   }}


Where the FSMAction class contains a method like this:

void FSMAction::operator()(char ch,ostream & out){   pVec[object_state_]->action(ch,out,object_state_); // filters ch and resets object_state_.}


C++, what a brilliant programming language!

--random.
--random_thinkerAs Albert Einstein said: 'Imagination is more important than knowledge'. Of course, he also said: 'If I had only known, I would have been a locksmith'.

This topic is closed to new replies.

Advertisement