Signalling failure by throwing in a constructor
Question
May a C++ constructor throw an exception? Explain what happens if it does.
Short answer
Yes, and it is the standard way to report a failed construction. The object is never considered constructed, so its destructor does not run, but already-built members and base classes are destroyed automatically. Hence raw resources grabbed earlier in the constructor leak unless they are held by RAII objects such as smart pointers.
Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.4, p.226; question and answer rewritten by SelfMadeQuant.com.
See the hint and the full worked solution in the question bank (free account).
Open the worked solution