Half Built Singleton
Double-checked locking, with a real mutex and the second check present:
static Registry* g_instance = nullptr;
static std::mutex g_mutex;
Registry* get() {
if (g_instance == nullptr) { // 1: fast path, no lock
std::lock_guard<std::mutex> lk(g_mutex);
if (g_instance == nullptr) { // 2: re-check under the lock
g_instance = new Registry(); // 3
}
}
return g_instance; // 4
}
The mutex is correct, the second check is correct, and on x86 every test passes. Callers still occasionally receive a Registry whose constructor has not finished. Which statement identifies the defect?
Sign in to answer questions and track your progress
Sign In