LoginSignup
12
14

More than 5 years have passed since last update.

shared_ptrを使用したSingletonの実装

Last updated at Posted at 2016-06-28

新しいの書きました
アロケータを指定できて参照がなくなった時点で破棄されるSingleton

参照が0になった時点で破棄されるsingleton

普段私が使っているsingletonを他で見ることがないので書き残しておく

実装

コピー禁止の処理とか書くの忘れてました。
適当に補完しておいてください。

コード書き換えたついでに書きました。

#include <memory>

template <typename T> class singleton
{
protected:
  singleton() {}
public:
  virtual ~singleton() {}

  singleton( singleton const& ) = delete;
  singleton& operator=( singleton const& ) = delete;

public:
  static std::shared_ptr<T> get_instance()
  {
    auto ret_ptr = instance_.lock();
    if( !ret_ptr )
    {
      ret_ptr   = std::shared_ptr<T>( new T{} );
      instance_ = std::weak_ptr<T>( ret_ptr );
      return ret_ptr;
    }

    return instance_.lock();
  }

private:
  using allocator = typename singleton_allocator<T>::type;
  static std::weak_ptr<T> instance_;
}; // class singleton


template <typename T> std::weak_ptr<T>  singleton<T>::instance_;

使い方

class A : public singleton<A>
{
private:
  frinend class singleton<A>;
  A() {} // コンストラクタをprivateに
};

int main()
{
  std::shared_ptr<A> a1 = A::get_instance(); // ここでインスタンスが生成される
} // スコープを抜けて参照が0になった時点で破棄される

注意点など

createやdestroyを呼ぶ必要が無いのは良いですが他と比べるとわかりづらい気もします。

インスタンスが生成されてないタイミングで

A::get_instance();

だけを書くと生成した瞬間に破棄されます。

auto a = A::get_instance();

このように、必ず参照する変数を保持してください。

12
14
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14