if a constructor OR public member function throws an exception, will the objects destructor be called automatically?

Why not try it and see for yourself:

#include <iostream>

struct Foo {
  Foo(bool shouldThrow) { 
    if(shouldThrow) {
      std::cout << "Foo Constructor called, throwing exception..." << std::endl;
      throw 42;
    } else {
      std::cout << "Foo Constructor called, no throwing anything :)" << std::endl;
    };
  };
  ~Foo() {
    std::cout << "Foo Destructor called!" << std::endl;
  };

  void someMethod() {
    throw 69;
  };

};

struct Bar {
  Foo f;
  Bar() : f(false) {
    std::cout << "Bar Constructor called, throwing exception..." << std::endl;
    throw 17;
  };
  ~Bar() {
    std::cout << "Bar Destructor called!" << std::endl;
  };
};


int main() {
  std::cout << "\nTrying to create object Foo(true)..." << std::endl;
  try {
    Foo f(true);
  } catch (int e) {
    std::cout << "Caught exception number " << e << std::endl;
  };

  std::cout << "\nTrying to create object Foo(false) and calling someMethod..." << std::endl;
  try {
    Foo f(false);
    f.someMethod();
  } catch (int e) {
    std::cout << "Caught exception number " << e << std::endl;
  };

  std::cout << "\nTrying to create object Foo(true) dynamically..." << std::endl;
  try {
    Foo* fp = new Foo(true);
    delete fp;
  } catch (int e) {
    std::cout << "Caught exception number " << e << std::endl;
  };

  std::cout << "\nTrying to create object Foo(false) dynamically and calling someMethod..." << std::endl;
  try {
    Foo* fp = new Foo(false);
    fp->someMethod();
    delete fp;
  } catch (int e) {
    std::cout << "Caught exception number " << e << std::endl;
  };

  std::cout << "\nTrying to create object Bar..." << std::endl;
  try {
    Bar b;
  } catch (int e) {
    std::cout << "Caught exception number " << e << std::endl;
  };

  return 0;
};
This article has been dead for over six months. Start a new discussion instead.