Execute-Around Pointer Idiom

 

#include <iostream>
#include <vector>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> v;

    cout <<"before: " <<v.size() <<endl;
    v.push_back(0);
    cout <<"after: " <<v.size() <<endl;

    cout <<"before: " <<v.size() <<endl;
    v.push_back(0);
    cout <<"after: " <<v.size() <<endl;

    cout <<"before: " <<v.size() <<endl;
    v.push_back(0);
    cout <<"after: " <<v.size() <<endl;

    // ....
    // Tedious.

    return 0;
}

  Have you written this code ever?

  Most people have such experience, so have I. We want to do something around each function call, so we have to write lots of codes, which is neither elegant nor maintainable.

 

Solution:

#include <iostream>
#include <vector>
using namespace std;

class VectorWraper
{
    class Around
    {
    public:
        Around(vector<int> *p) : m_p(p) 
        {
            // Before execution.
            cout <<"before: " <<m_p->size() <<endl;
        }
        ~Around()
        {
            // After execution.
            cout <<"after: " <<m_p->size() <<endl;
        }

        vector<int> *operator->()
        {
            cout <<"doing." <<endl;
            return m_p; 
        }

        vector<int> *m_p;
    };

    vector<int> m_val;
public:
    Around operator->()
    { return Around(&m_val); }          // Addtional codes will be executed by ctor and dtor, which is 
                                        // around the real called function. That's the trick.
};

int _tmain(int argc, _TCHAR* argv[])
{
    VectorWraper t;

    t->push_back(1);                    // Use '->' instead of '.' to dereferencing.

    return 0;
}

  This trick replace traditional dereference operator '*' with operator '->', and warp additional jobs by the  execution of ctor and dtor of an temporary object. Fantastic!

  Remember: '.' can't be overloaded.

posted @ 2012-09-19 15:59  walfud  阅读(428)  评论(1编辑  收藏  举报