Medium
std::call_once with an initializer that throws
This version replaces manual double-checked locking with std::call_once. If the initializer function throws on the first attempt (e.g. resource exhaustion), and a second thread is concurrently blocked in call_once on the same once_flag, what happens?
main.cpp
class Widget {
public:
static Widget* instance() {
std::call_once(flag_, [] {
ptr_ = new Widget(); // may throw std::bad_alloc
});
return ptr_;
}
private:
static Widget* ptr_;
static std::once_flag flag_;
};
Widget* Widget::ptr_ = nullptr;
std::once_flag Widget::flag_;4 of 44 in Design Patterns