c++ - Access "this" pointer of concrete class from interface -
after writing test, determined this
pointer in interface not equal this
pointer of concrete class, meaning can't use c-style cast on it.
class abstractbase {...}; class aninterface { public: aninterface() {...} // need abstractbase * here ~virtual aninterface() {...} // , here }; class concrete : public abstractbase, public aninterface {};
my interface needs base class pointer concrete class inheriting in constructor , destructor in order handle interface related registration , deregistration.
every concrete object inherits interface needs inherit abstract base class first, first in layout.
for constructor not hard, can add pointer in interface constructor , pass this
concrete class. destructor doesn't have parameters, in dark there.
the solutions came far come overhead:
1 - store pointer in interface used in destructor - adds in 1 pointer worth of memory overhead
class aninterface { public: aninterface(abstractbase * ap) {...} ~virtual aninterface() {...} // , here private: abstractbase * aptr; }; ... concrete() : aninterface(this) {}
2 - create abstract method in interface , implement return this
in concrete class - adds in overhead of indirection virtual call
class aninterface { virtual abstractbase * getptr() = 0; }; class concrete : public abstractbase, public aninterface { abstractbase * getptr() { return this; } };
3 - dynamic_cast
worse
is there more efficient way achieve this?
imo if decoupling between base class , interface needed, both solution 1 , 2 have tolerable overheads, nothing problem on contemporary hardware.
but since interface designed work functionality, provided in base class, maybe decoupling not thing.
i mean if problem inheriting multiple interfaces inherit base class, or "dreaded diamond" problem inheritance, can use virtual inheritance.
Comments
Post a Comment