More C++ Idioms/Execute-Around Pointer

= Execute-Around Pointer =

Intent
Provide a smart pointer object that transparently executes actions before and after each function call on an object, given that the actions performed are the same for all functions. This can be regarded as a special form of aspect oriented programming(AOP).

Also Known As
Double application of smart pointer or decorator.

Motivation
Often times it is necessary to execute a functionality before and after every member function call of a class. For example, in a multi-threaded application it is necessary to lock before modifying the data structure and unlock it afterwards. In a data structure visualization application might be interested in the size of the data structure after every insert/delete operation.

Such a repetition of function calls is error-prone and tedious. It would be ideal if calls to visualizer could be automated. Visualizer could be used for std::list as well. Such functionality which is not a part of single class but rather cross cuts multiple classes is commonly known as aspects. This particular idiom is useful for designing and implementing simple aspects.

Solution and Sample Code
Overloaded -> operator of visualizableVector creates a temporary proxy object and it is returned. Constructor of proxy object logs size of the vector. The overloaded -> operator of proxy is then called and it simply forwards the call to the underlying vector object by returning a raw pointer to it. After the real call to the vector finishes, destructor of proxy logs the size again. Thus the logging for visualization is transparent and the main function becomes free from clutter. This idiom is a special case of Execute Around Proxy, which is more general and powerful.

The real power of the idiom can be derived if we combine it judiciously with templates and chain the overloaded -> operators.

Related Idioms
Smart Pointer