[cfe-dev] The really scary part of noexcept

Sebastian Redl sebastian.redl at getdesigned.at
Sun Mar 20 07:15:28 PDT 2011


Hi,

There's one small piece of the noexcept specification left to implement. It's not only scary, it's also fiendishly difficult to find, being the only part of noexcept that isn't within [except]. [class.dtor]p3 says:

"A declaration of a destructor that does not have an exception-specification is implicitly considered to have the same exception-specification as an implicit declaration."

This means that destructors suddenly grow exception specifications, and they may be really, really wrong. Consider this little class, which could be used as an RAII guard.

class TransactionGuard {
  DatabaseConnection& m_conn;
public:
  TransactionGuard(DatabaseConnection& conn) : m_conn(conn) {}
  ~TransactionGuard() {
    if (std::unhandled_exception()) { // if we're being destructed due to an exception being thrown
      try { conn.rollback(); } catch(...) {} // rollback and swallow any errors, or we terminate
    } else {
      conn.commit(); // otherwise commit, and let exceptions escape
    }
  }
};

The above destructor would suddenly grow an exception-specification. Specifically, because it has no object data members, the exception-specification would be empty: it would be noexcept(true). If the conn.commit() call throws, the program would immediately terminate instead of letting the exception escape.

Scary? Hell, yes! Useful? That too, when you consider that most constructors don't throw.

Now, the rationale for this part of the standard was that throwing destructors are high-risk parts of a program, so programmers would know where they are and check them when upgrading to C++0x. This argument makes sense - if you consider the C++0x transition global and instantaneous. But in reality, with compilers adopting different parts of the standard in different order, it's a headache.

So my question is, how should we implement this in Clang? Simply put it under C++0x? Have it enabled in C++0x by default, but add a switch to turn it off? Add an explicit switch to turn it on?

Sebastian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20110320/50003c51/attachment.html>


More information about the cfe-dev mailing list