ProgrammingHardProduct-company placement · C++
In C++11 and later, which statement about this 'Meyers singleton' is correct?
In C++11 and later, which statement about this 'Meyers singleton' is correct?
Logger& instance() {
static Logger log;
return log;
}- A. Initialisation of log is thread-safe: if several threads call instance() at once, exactly one constructs it
- B. It is not thread-safe unless a mutex is added
- C. log is constructed before main starts
- D. A new Logger is created on every call
Correct answer: A. Initialisation of log is thread-safe: if several threads call instance() at once, exactly one constructs it
Since C++11 the language guarantees that a block-scope static is initialised exactly once even under concurrent first calls (other threads wait). It is constructed on first use, not before main.
More OOP with C++ and Java questions
- How many of these are resolved at COMPILE time in C++? (i) Which function body a call to a non-virtual member function through a…
- What is printed? java String b = "java"; String a = "ja" + "va"; String c = "ja"; String d = c + "va"; final String e = "ja"; String f = e…
- What is printed? java class A { void f(Object o) { System.out.print("AO "); } void f(String s) { System.out.print("AS "); } } class B…
- What is printed? java class P { String n = "P"; String get() { return n; } } class C extends P { String n = "C"; String get() { return n…
- What is printed? java class P { P() { show(); } void show() { System.out.print("P "); } } class C extends P { int x = 5; final int y = 7…
- What is printed? java static int f() { int x = 1; try { return x; } finally { x = 2; } } static StringBuilder g() { StringBuilder sb = new…