Adib Adib - 1 year ago 74
C++ Question

What happens if an exception occur before than static local variables are initialized?

When are static local variables initialized?
If an exception is thrown in a constructor, is the object considered constructed? Will the destructor be called?

consider fallowing code :

#include <iostream>
#include <exception>

int x = 0;

class A {
A() {
std::cout << 'a';
if (x++ == 0) {
throw std::exception();
~A() { std::cout << 'A'; }

class B {
B() { std::cout << 'b'; }
~B() { std::cout << 'B'; }
A a;

void foo() { static B b; }

int main() {
try {
catch (std::exception &) {
std::cout << 'c';

output : acabBA

The first time foo() is called, b is attempted initialized. Its constructor is called, which first constructs all member variables. This means A::A() is called, printing a. A::A() then throws an exception, the constructor is aborted, and neither b or B::a are actually considered constructed.

why b was not initialized the first time ?

Answer Source

The initialization of a block-scope variable with static storage duration is attempted every time control passes over the variable definition until it succeeds.

From [stmt.dcl]/4:

Dynamic initialization of a block-scope variable with static storage duration (3.7.1) or thread storage duration (3.7.2) is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration.

The construction of an object of type B can of course not complete if the construction of any of its members throws an exception.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download