You've answered 1 of 171 questions correctly. (Clear)
Question #14 Difficulty:
According to the C++23 standard, what is the output of this program?
#include <iostream>
class A {
public:
A() { std::cout << "a"; }
~A() { std::cout << "A"; }
};
class B {
public:
B() { std::cout << "b"; }
~B() { std::cout << "B"; }
};
class C {
public:
C() { std::cout << "c"; }
~C() { std::cout << "C"; }
};
A a;
void foo() { static C c; }
int main() {
B b;
foo();
}
Correct!
§[basic.start.dynamic]¶5 in the standard:
It is implementation-defined whether the dynamic initialization of a non-block non-inline variable with static storage duration is sequenced before the first statement of main or is deferred. If it is deferred, it strongly happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the same translation unit as the variable to be initialized.
Since A()
is not constexpr
, the initialization of a
is dynamic. There are two possibilities:
- a
is initialized before main()
is called.
- The initialization of a
is deferred, but it is initialized before any non-inline function in the same translation unit as it is used. And since main()
and a
are defined in the same translation unit, it is still initialized before main()
.
When execution reaches B b
, it is initialized as normal. Static local variables are initialized the first time control passes through their declaration, so c
is initialized next. As main()
is exited, its local variable b
goes out of scope, and is destroyed. Finally, all static variables are destroyed in reverse order of their initialization, first c
, then a
.
You can explore this question further on C++ Insights or Compiler Explorer!
Mode : Training
You are currently in training mode, answering random questions. Why not Start a new quiz? Then you can boast about your score, and invite your friends.
Contribute
Android app
Get Sergey Vasilchenko's CppQuiz Android app.
C++ Brain Teasers
Get the book, support the site!