使用设计模式中的单例模式来实现C++的boost库

2020-01-06 14:38:35王冬梅

跟最初方案一的区别是在main函数前就初始化了单例,不会有线程安全问题。

最终boost
上面为了说明清楚点去除了模版,实际使用是用模版,不用写那么多重复代码,这是boost库的模板实现:


template <typename T>
struct Singleton
{
  struct object_creator
  {
    object_creator(){ Singleton<T>::instance(); }
    inline void do_nothing()const {}
  };
 
  static object_creator create_object;
 
public:
  typedef T object_type;
  static object_type& instance()
  {
    static object_type obj;
    //据说这个do_nothing是确保create_object构造函数被调用
    //这跟模板的编译有关
    create_object.do_nothing();
    return obj;
  }
 
};
template <typename T> typename Singleton<T>::object_creator Singleton<T>::create_object;
 
class QMManager
{
protected:
  QMManager();
  ~QMManager(){};
  friend class Singleton<QMManager>;
public:
  void do_something(){};
};
 
int main()
{
  Singleton<QMManager>::instance()->do_something();
  return 0;
}

其实Boost库这样的实现像打了几个补丁,用了一些奇技淫巧,虽然确实绕过了坑实现了需求,但感觉挺不好的。



注:相关教程知识阅读请移步到C++教程频道。