vtable on stack

Patrick Horgan phorgan1@yahoo.com
Tue Feb 2 21:35:00 GMT 2010


Axel Freyn wrote:
> Hi Patrick,
> On Tue, Feb 02, 2010 at 09:56:19AM -0800, Patrick Horgan wrote:
>   
>>> 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;}
>>> };
>>>   
>>>       
>> I like this whole thing, but wouldn't operator* be more natural to  
>> return the reference?
>>     
> Even if we are probably quite off-topic now: Yes, you are absolutely
> right. I only used () as, when I first (already a few years ago) wrote a
> similar class (a bit more complex) which I wanted to use for fast
> matrix-vector calculations, I realized a problem with "*": it can lead
> to unresolved overloads when you write something like
> class GeneralCache { ... };
> class Cache : public GeneralCache { ... };
> ... operator * (const GeneralCache &, const GeneralCache & );
>   
Yes, I see this, but this is the nature of the beast.  Even without user 
defined types you can get exactly this same problem and sometimes need 
parenthesis to make clear what you mean.  When you override operator() 
people expect the meaning to be function or constructor.

> Cache a, b, c;
> c = a * b;
> Now is "*" dereferencing b, or is it multiplying a and b? 
>   
Frustrating when you try to come up with a good example off the top of 
your head and you can't think of one, huh?  It always happens to me 
too.  Of course this would only make sense for the binary operator*, the 
unary would one just be a syntax error, and current gcc would use the 
binary one without warnings.

Patrick



More information about the Gcc-help mailing list