[ create a new paste ] login | about

Link: http://codepad.org/mPaOgxoI    [ raw code | output | fork ]

aaronla - C++, pasted on Oct 21:
    #include <iostream>
    #include <iomanip>
    using namespace std;

    template <class T>
    class Holder {
      bool do_destroy;
      union { char data[sizeof(T)];
              void* p; }
        aligned_store;

      T* ptr() { return static_cast<T*>(static_cast<void*>(aligned_store.data)); }
    
    public:
      Holder() : do_destroy(true) {
        new (ptr()) T();
      }
      ~Holder() {
        if(do_destroy) ptr()->~T();
      }
      void forget() { do_destroy = false; }
    };

    struct S {
      S() { cout << "S()" << endl; }
      ~S() { cout << "~S()" << endl; }
    };

    int main() {
      cout << "make, then destroy as normal" << endl;
      { Holder<S> hs; }
      cout << "this time, lets forget to destroy" << endl;
      { Holder<S> hs; hs.forget(); }
      cout << "it's gone!" << endl;
    }


Output:
1
2
3
4
5
6
make, then destroy as normal
S()
~S()
this time, lets forget to destroy
S()
it's gone!


Create a new paste based on this one


Comments: