Rooot.net

  • Increase font size
  • Default font size
  • Decrease font size
Living in a wooden world.
Home Development Code C++ member function pointers and delegates

C++ member function pointers and delegates

Delegates is a concept widely used in design patterns like Observer or Strategy.

Standard C++ doesn't provide delegates, but this can be implemented using member function pointers. The problem is that C++'s object-oriented function pointers have a complicated syntax and have wierd behavior when dealing with inherited classes.

There has been a lot of discussion on this topic and many implementations exists.

Existing solutions

Make sure to check out Don Clugston's FastDelegate. His article provides an in-depth analysis of member function pointer internals. Unfortunately the implementation he provides is not C++ standard-compliant.

Boost's function tends to be slow because it requires dynamic memory allocation, but is also more flexible.

Libsigc++ is a callback system used in many projects (gtkmm, GTK+ & Gnome) and can be used to implement delegates.

Elbert Mai's CPPCallback use the work from Don Clugston and Sergey Ryazanov and propose a fast and standard-compliant implementation.

Lewis Van Winkle's PlusCallback is similar to Elbert Mai's CPPCallback and does not use macro. It also includes a useful benchmark script.

Benchmarking

Based on Lewis Van Winkle's work, I extended the benchmark script he created to compare performance of each implementation.

C++ member function pointer benchmark

Intel(R) Core(TM)2 Duo CPU T7300 @ 2.00GHz / g++ 4.6.1


Libsig++ has a very expensive create and copy cost and is the slowest.
CPPCallback turns out to be the fastest and surprisingly its create and copy operation have no cost (couldn't figure out why).

If you need performance using delegates, CPPCallback or PlusCallback would be good choices.
I included the updated benchmark script from PlusCallback, please let me know if you get different results.

Sources

http://www.codeproject.com/KB/cpp/FastDelegate.aspx
http://www.boost.org/doc/libs/1_45_0/doc/html/function.html
http://libsigc.sourceforge.net/
http://codeplea.com/pluscallback
http://www.codeproject.com/KB/cpp/CPPCallback.aspx

Comments
Add New Search
Write comment
Name:
Email:
 
Website:
Title:
UBBCode:
[b] [i] [u] [url] [quote] [code] [img] 
 
 
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
 
Please input the anti-spam code that you can read in the image.

3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."