123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- #include <mutex>
- #include <stdexcept>
- void do()
- {
- static std::mutex mutex;
- std::lock_guard<std::mutex> lock(mutex);
- std::ofstream file("file.txt");
- if (!file.is_open())
- throw std::runtime_error("Can't open file!");
- file << "Add some text!";
- } // if exception is thrown, we skip the writing to file and the scope closes, releasing all objects
- // State Pattern
- class Context {
- public:
- void request() {}
- };
- class State {
- public:
- virtual void handle() {}
- };
- class RealState : public State
- {
- void handle() override { (void)(0); }
- };
- class GreatState : public State
- {
- void handle() override { (void)(0); }
- };
- // Visitor
- class CarElement {};
- class CarElementVisitor {
- public:
- };
- // Double-checked locking with singleton
- class Singleton {
- public:
- static Singleton* instance();
- private:
- Singleton() = default;
- static std::atomic<Singleton*> s_instance;
- static std::mutex s_mutex;
- };
- Singleton* Singleton::GetInstance()
- {
- Singleton* p = s_instance.load(std::memory_order_acquire);
- if (!p)
- {
- std::lock_guard<std::mutex> lock(s_mutex);
- p = s_instance.load(std::memory_order_relaxed);
- if (!p)
- {
- p = new Singleton();
- s_instance.store(p, std::memory_order_acquire);
- }
- }
- return p;
- }
|