Re: vtable on stack

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Frank,
> Using references is a good idea. Indeed, B::f() gets called.
>
> I agree that making the object const, is quite a drawback and having a  
> temporary object living parallel is that good either.
There is also another possibilty you could maybe think about: If you
create an additional structure, which "caches" the pointer to A or B and
returns references to it, you can have this new structure living on the
stack - and do with it whatever you want (e.g. you can insert it into a
std::vector without problems):
 
struct Cache{
  Cache( A* _a):a(_a){}
  A *a;
  A& operator()(){ return *a;}
};


int main() {
    A* x = new B();
    x->f();         // Class B

    Cache y = new B();
    y().f();          // Class A
}

this prints also "Class B".
However, as always there are some drawbacks...
 - my example will introduce memory-leaks, as the pointers are never
   deleted -> add a destructor to "Cache"
 - if you want to copy "y", you have to be careful as to what you are
   doing (shall the object pointed to be "a" also be copied - or shall
   both "Cache"'s use the same A? If you copy it: Which
   copy-constructor - the one of A or the one of B? If not: then each
   Cache has to count, how often the object A is used - in order to be
   able to write a working destructor...

Maybe the most powerful way would be:
 - add a virtual function "A* make_copy()" to struct A, which returns a
   copy of A
 - overload it in struct B
 - overload the Copy-Constructor and the assignement-operator for struct
   Cache, such that they use "make_copy" (this guarantees that
   "Cache y = new B();  Cache y1 = y;"  and "Cache y = new A(); Cache y1
    = y" are treated differently.
 - Add a destructor to Cache, which deletes the pointer
 - If - in addition - you also add "const A& operator()()const", you can
   also use "Cache" when it is a constant.

With that, you would simulate quite well a "virtual class on the stack"
- you can do almost everything with it. The only drawback I see is the
necessity to explicitely write "y()" instead of "y" (or some arbitrary
other memberfunction like "*y" or "y.get()"), which returns the
reference to A*.


Axel

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux