简体   繁体   中英

MFC MessageMap and Virtual functions

MFC uses an efficient way to deal with space consumption and complexity issues involved with virtual functions. For examples, the image below demonstrates how functions in the class hierarchy are fetched. This implementation is space efficient, easy to understand, and also seems to be efficient.

MFC消息映射处理

My question is, why core C++ doesn't use the same way to reduce the complexity of compiler and to get rid of vtables? Perhaps this implemention has efficiency issues as well?

C++ polymorhphism is implemented more or less the same in every compiler; each object has a vtable (equivalent of messageEntries ) which is dereferenced in order to get actual function address.

C++ polymorphism is better than MFC, because it doesn't require macros or any other fiddling; the only change is the virtual keyword, and the rest of the code stays the same.

What about ease of use?

// Compare
object_ref._messageEntries[WM_PAINT](); // MFC
// vs.
object_ref.paint(); // C++

Regarding efficiency, virtual methods add another pointer dereference, that can in theory be avoided. When writing performance-critical code, you want to reduce number of executed operations, dumping run-time polymorphism alltogether. Built-in language solution certainly isn't slower than MFC's, though.

MFC's solution pros show when dispatching events. In this case, having indexable function array is a big plus, because it eases passing events through components.

If you look closer into MFC classes you will see lots of virtual methods. What you see on above diagram is a message driven mechanizm used in lots of GUI frameworks - even in a new ones like used on android.

Main purpose for message driven communication is to make sure all GUI related stuff is being done on GUI thread. Also all messages are being queued, so they are managed in some order. This actually has nothing to do with how C++ was designed or should be designed.

If you want to look into frameworks that does not use virtual methods then look into WTL/ATL and CRTP:

http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM