2006-11-04
■[プログラミング][C/C++]シングルトンネタ続き

シングルトンをd:id:crimsonwoods:20061020のようなパターンとして実装するのに反対な理由。
(シングルトンなクラスをAとし、Aを使う側をBとする)
- Aをシングルトンとして規定することで、AとBの間にシングルトンであるという依存性が形成されてしまう
- Aをシングルトンでなくファクトリで生成したくなった場合などの修正コストがでかい
- ダブルチェックロッキングのロジックなど、インスタンスの生成過程に関するロジックをAに加えなければならない
ということでtemplateを使ってSingletonにするラッパーを考えてみた。
template < class _Ty, class _Counter > class singleton_shared_ptr
{
private:
mutable _Ty* _ptr;
mutable _Counter _shared_counter;
public:
singleton_shared_ptr( _Ty* ptr, _Counter* cnt )
: _ptr( ptr ), _shared_counter( cnt )
{
if( 0 != _shared_counter )
{
++*_shared_counter;
}
}
singleton_shared_ptr( const singleton_shared_ptr& ptr )
: _ptr( ptr._ptr ), _shared_counter( ptr._shared_counter )
{
if( 0 != _shared_counter )
{
++*_shared_counter;
}
}
~singleton_shared_ptr()
{
if( 0 != _shared_counter )
{
--*_shared_counter;
}
}
singleton_shared_ptr& operator = ( const singleton_shared_ptr& ptr )
{
if( this == &ptr )
{
return *this;
}
if( 0 != _shared_counter )
{
--*_shared_counter;
}
_ptr = ptr._ptr;
_shared_counter = ptr._shared_counter;
if( 0 != _shared_counter )
{
++*_shared_counter;
}
return *this;
}
_Ty* operator -> () const
{
return _ptr;
}
_Ty& operator * () const
{
return *_ptr;
}
};
tempalte < class _Ty, class _Counter = size_t, class _Ptr = singleton_shared_ptr< _Ty, _Counter > > class singleton
{
private:
static _Ty* _instance;
static _Counter _shared_counter;
public:
static _Ptr instance()
{
if( 0 == _instance )
{
_instance = new _Ty();
}
return _Ptr( _instance, &_shared_counter );
}
static void release()
{
if( 0 == _shared_counter )
{
delete _instance;
_instance = 0;
}
}
};
tempalte < class _Ty, class _Counter, class _Ptr > _Ty* singleton::_instance = 0;
tempalte < class _Ty, class _Counter, class _Ptr > _Counter* singleton::_shared_counter = 0;
一応共有カウント付き。どうなんだろうなこれ。
コメントを書く
トラックバック - http://d.hatena.ne.jp/crimsonwoods/20061104/1162608678
リンク元
- 64 http://nothingnothink.blogspot.com/2007/10/singletonwrapper.html
- 9 http://www.google.co.jp/search?hl=ja&q=C++/CLI+シングルトン&btnG=検索&lr=
- 9 http://www.google.co.jp/search?hl=ja&q=CLI+シングルトン&lr=&aq=f&oq=
- 8 http://www.google.co.jp/search?hl=ja&q=シングルトン C++&lr=
- 6 http://www.google.co.jp/search?sourceid=navclient&hl=ja&ie=UTF-8&rlz=1T4GGLJ_jaJP221JP221&q=C+++cli+シングルトン
- 4 http://search.yahoo.co.jp/search?p=ダブルチェックロッキング&ei=UTF-8&fr=top_v2&x=wrt&meta=vc=
- 4 http://www.google.co.jp/hws/search?hl=ja&q=シングルトン+C+++template&client=fenrir&adsafe=off&safe=off&lr=lang_ja
- 4 http://www.google.co.jp/search?q=シングルトン+Visual+Studio+2008&lr=lang_ja&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:ja:official&client=firefox-a
- 4 http://www.google.co.jp/search?q=C++/CLI+シングルトン&sourceid=navclient-ff&ie=UTF-8&rls=GGGL,GGGL:2006-26,GGGL:ja
- 3 http://a.hatena.ne.jp/uskz/?gid=290138

