RyanJeong / design-pattern

Gang of Four Design Patterns
Apache License 2.0
0 stars 0 forks source link

Thread-safe Singleton using unique_ptr #2

Open RyanJeong opened 2 years ago

RyanJeong commented 2 years ago
// singleton.cc
// g++ singleton.cc -std=c++11 -lboost_system
#include "singleton.hpp"

#include <iostream>

#include <boost/thread/thread.hpp>

std::unique_ptr<Singleton> Singleton::instance = nullptr;
std::once_flag Singleton::flag;

Singleton& Singleton::GetInstance() {
    std::call_once(Singleton::flag, []() {
      Singleton::instance.reset(new Singleton);
  });
    std::cout << "Get Instance." << std::endl;

    return *Singleton::instance;
}

int main() try {
  Singleton::GetInstance();
    Singleton::GetInstance();
    Singleton::GetInstance();

    return 0;
} catch (std::exception& e) {
    std::cout << e.what() << std::endl;
}
// singleton.hpp
#pragma once

#include <memory>  // unique_ptr
#include <mutex>  // once_flag

class Singleton final {
 public:
  ~Singleton() = default;
  Singleton(const Singleton&) = delete;
  Singleton(Singleton&&) = delete;
  Singleton& operator=(const Singleton&) = delete;
  Singleton& operator=(Singleton&&) = delete;
  static Singleton& GetInstance();

 private:
  Singleton() = default;
  static std::unique_ptr<Singleton> instance;
  static std::once_flag flag;
};