[aspectc-user] AspectC++ and singletons?

Mike Mortensen mmo at fc.hp.com
Fri Nov 23 19:13:23 CET 2007

Until experimenting with implementing singleton without the regular code 
switching to
a static call, I hadn't thought about the heap versus local use of 
constructors in C++.

Also, related to that is the fact that not only do the automatic 
instantiations normally get
freed when exiting the scope they were created in, but also that if the 
user (in the 'normal'
non-aspect code) ever called 'delete object;' after creating it (on our 
aspectualized singleton
object), it would mess things up (since all other objects allocated were 
now -- thanks to an
aspect -- pointing to the one singleton).

Thus, in addition to handling object creation in the heap versus local 
stack (automatic), an
aspect would have to prevent the destructor from removing the memory.  
However, AspectC++
provides the same kind of 'execution' access to the destructor, which 
doesn't prevent the
actual freeing of the memory.

This is not a criticism of AspectC++ -- rather, I think the correct (or 
perhaps preferred) way
would be for the client to use a static 'factory' creation function:

      ShapeRegistry *sr1 = ShapeRegistry::createShapeRegistry();

and then allow the aspect to augment that to either be or regular 
factory or singleton...

Thanks for everyone's feedback!

> Olaf Spinczyk schrieb:
>> Hi Mike,
>> at the moment AspectC++ does not support the interception of 
>> constructor calls on the client side. The 'construction' advice is 
>> something like 'execution' advice for the constructor. When the 
>> constructor is executed, the memory for the object has already been 
>> allocated. Therefore, this language feature doesn't help you.
> Just an idea: Memory allocation on the heap could be influenced by 
> introducing a class-level operator new into the class that always 
> returns the address of the one-and-only singleton. However, after an 
> allocation the constructor is executed anyway. This means that we had 
> a situation where an object is constructed multiple times at the same 
> memory location. It might be possible to catch this situation in the 
> constructor body, the the constructors of base classes and class-type 
> member variables have already been executed by this time.
> Another thing is that all this does not help for static or automatic 
> instantiations of the class, as operator new is not involved in these 
> cases.
> Daniel

More information about the aspectc-user mailing list