Virtual Methods or Function Pointers

后端 未结 8 1449
春和景丽
春和景丽 2020-12-07 11:31

When implementing polymorphic behavior in C++ one can either use a pure virtual method or one can use function pointers (or functors). For example an asynchronous callback c

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 12:24

    The primary problem with Approach 2 is that it simply doesn't scale. Consider the equivalent for 100 functions:

    class MahClass {
        // 100 pointers of various types
    public:
        MahClass() { // set all 100 pointers }
        MahClass(const MahClass& other) {
            // copy all 100 function pointers
        }
    };
    

    The size of MahClass has ballooned, and the time to construct it has also significantly increased. Virtual functions, however, are O(1) increase in the size of the class and the time to construct it- not to mention that you, the user, must write all the callbacks for all the derived classes manually which adjust the pointer to become a pointer to derived, and must specify function pointer types and what a mess. Not to mention the idea that you might forget one, or set it to NULL or something equally stupid but totally going to happen because you're writing 30 classes this way and violating DRY like a parasitic wasp violates a caterpillar.

    Approach 3 is only usable when the desired callback is statically knowable.

    This leaves Approach 1 as the only usable approach when dynamic method invocation is required.

提交回复
热议问题