1

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 {
public:
  A() {
    std::cout << 'a';
    if (x++ == 0) {
      throw std::exception();
    }
  }
  ~A() { std::cout << 'A'; }
};

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

void foo() { static B b; }

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

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 ?

Adib
  • 723
  • 5
  • 22

1 Answers1

3

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • and in order of destruction of static variable it wont have any affect ? – Adib Nov 26 '16 at 18:11
  • @Adib: I don't understand - effect on what? Static variables are destroyed in reverse order of their construction (but of course this is only relevant if construction actually took place). – Kerrek SB Nov 26 '16 at 18:12
  • yes exactly i wanted to know this as static varible was not constructed before exception then it wont change order of destruction . right ? – Adib Nov 26 '16 at 18:16
  • @Adib: Only objects get destroyed. If there is no object, there is nothing to destroy. – Kerrek SB Nov 26 '16 at 20:02