Why can't we use “virtual inheritance” in COM?

后端 未结 3 2036
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 12:39

I have read some vague statement that virtual inheritance doesn\'t provide the memory structure required by COM, so we have to use the normal inheritance. Virtual inheritanc

3条回答
  •  [愿得一人]
    2020-12-29 13:02

    A COM coclass can implement multiple interfaces but each individual interface must implement a v-table with pointers to all of the methods brought in by its 'base' interfaces. At a minimum IUnknown. If it, say, implements IPersistFile then it must provide an implementation of the three IUnknown methods as well as IPersist::GetClassID. And the IPersistFile specific methods.

    Which happens to match the behavior of most C++ compilers when they implement non-virtual multiple inheritance. The compiler sets up individual v-tables for each inherited (pure abstract) class. And fills it with method pointers so that one common class method implements all methods that the interfaces have in common. In other words, no matter how many interfaces are implemented, they all are serviced by one class method like QueryInterface, AddRef or Release.

    Exactly the way you'd want it to work. Having one implementation of AddRef/Release makes reference counting simple to keep the coclass object alive, no matter how many different interface pointers you hand out. QueryInterface is trivial to implement, a simple cast provides the interface pointer to a v-table with the correct layout.

    Virtual inheritance is not required. And most likely would break COM because the v-tables no longer have the required layout. Which is tricky for any compiler, review the /vm options for the MSVC compiler for example. That COM so uncannily is compatible with the typical behavior of a C++ compiler is not an accident.

    Btw, this all hits the fan when a coclass want to implement multiple interfaces that have a method name in common that isn't meant to do the same thing. That's a pretty big oops and hard to deal with. Mentioned in ATL Internals (DAdvise?), I sadly forgot the solution.

提交回复
热议问题