myoptional的ななにか

boost::optionalが初期化を遅延できることを知ったのでへぇ〜と思ってたらふとなんとな〜く思いついたのでちょっと実装してみた。

#include <iostream>
#include <boost/utility.hpp>
using namespace std;
 
template<typename T>
class myoptional {
        public:
                myoptional() : created( false ) {}
                ~myoptional() {
                        if( created )
                                reinterpret_cast<T*>(obj)->~T();
                }
                template<typename U>
                T* create( const U &u ) {
                        if( !created ) {
                                new ( reinterpret_cast<void*>( obj ) ) T( u );
                                created = true;
                        }
                        return reinterpret_cast<T*>( obj );
                }
                void del() {
                        if( created ) {
                                reinterpret_cast<T*>(obj)->~T();
                                created = false;
                        }
                }
        private:
                bool    created;
                char    obj[sizeof(T)];
};
 
class A : boost::noncopyable {
        public:
                A( int i ) : _i( i ) {
                        cout << "created : " << _i << endl;
                }
 
                ~A() {
                        cout << "deleted : " << _i << endl;
                }
        private:
                int     _i;
};
 
int main()
{
        myoptional<A>   opt;
 
        cout << "create A(0) instance." << endl;
 
        opt.create( 0 );
 
        cout << "delete A(0) instance." << endl;
        
        opt.del();
 
        cout << "create A(1) instance." << endl;
 
        opt.create( 1 );
 
        cout << "delete A(1) instance." << endl;
 
        opt.del();
 
        cout << "create A(2) instance." << endl;
 
        opt.create( 2 );
 
        cout << "auto delete A(2) instance." << endl;
}

実行結果:http://ideone.com/eIMZc

何気なく書いたけど意外と通ったので少し驚き。
ただ、アラインメントは一切考慮していないので実用にはならないです。
#そもそもこんなものを使うぐらいならboost::optionalを使いましょう


このあたりの話はCryolite先生の
http://d.hatena.ne.jp/Cryolite/20051021
http://d.hatena.ne.jp/Cryolite/20051102
を読めばいい・・・のかな?