mardi 5 juillet 2016

Why exceptions from unique_ptr destructor terminates the program?

Take a look at this code which causes program to terminate without caching the exception.

#include <iostream>
#include <string>
#include <memory>
#include <stdexcept>
using namespace std;

struct test {
  ~test() noexcept(false) {
    throw runtime_error("-my-cool-exception-");
  }
};

int main()
{
  try {
    auto ptr = unique_ptr<test>(new test());
    //test t; // this is ok, without unique_ptr<test> it works fine.
  }
  catch(exception& e) {
    cout << "this is not called, the program is abarted";
    cout << e.what() << endl;
  }
  return 0;
}

This question is different from stack overflow question: throwing exceptions out of destructor.

The difference is that only when i use unique_ptr<test> the exception is not caught.

You can see the live code, edit and compile here http://cpp.sh/9sk5m

Aucun commentaire:

Enregistrer un commentaire