samedi 26 novembre 2016

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 {
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 never initialized the first time ?

Aucun commentaire:

Enregistrer un commentaire