导航:[首页]->[cpp]->[AtExit改进版本]

说道atexit大家都知道,不过下面的代码可以让函数退出(作用域失效)后立即执行某些析构操作。类似于自动内存管理,但是比它要跟灵活

    class AtExitBase{
    public:
        virtual ~AtExitBase(){}
    };

    template<typename OBJ,typename T,T(*FINI)(OBJ*obj)>
    class AtExit : public AtExitBase{
    public:
        AtExit(OBJ* ptr):m_ptr_(ptr){}
        virtual ~AtExit(){
            if(m_ptr_)
                FINI(m_ptr_);
        }
    private:
        OBJ*        m_ptr_;
    };

    class AtExitMng{
        typedef std::vector<AtExitBase*> AtExitVector;
        typedef AtExitVector::reverse_iterator Iter;
    public:
        ~AtExitMng(){
            for(Iter iter = m_vector_.rbegin();
                iter != m_vector_.rend();
                ++ iter)
            {
                delete *iter;
            }
        }

        template<typename OBJ,typename T,T(*FINI)(OBJ*obj)>
        void                Push(OBJ* ptr){
            AtExit<OBJ,T,FINI> *ptr_ = new AtExit<OBJ,T,FINI>(ptr);
            assert(ptr_);
            m_vector_.push_back(ptr_);
        }
    private:
        AtExitVector        m_vector_;
    };

    #include <cstdio>
    #include <cstdlib>
    int test(double * x){
        printf("FUNC:%s\n",__FUNCTION__);
        return 0;
    }


    int main(){
        double a = 0.0;

        AtExitMng mng_;
        mng_.Push<double,int,test>(&a);

        return 0;

    }