#include #include void do() { static std::mutex mutex; std::lock_guard 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 s_instance; static std::mutex s_mutex; }; Singleton* Singleton::GetInstance() { Singleton* p = s_instance.load(std::memory_order_acquire); if (!p) { std::lock_guard 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; }