Exceptional C++ mentions the following code
template <class T> class Stack
{
public:
Stack();
~Stack();
/*...*/
private:
T* v_; // ptr to a memory area big
size_t vsize_; // enough for 'vsize_' T's
size_t vused_; // # of T's actually in use
};
template<class T>
Stack<T>::Stack()
: v_(new T[10]), // default allocation
vsize_(10),
vused_(0) // nothing used yet
{
}
It says that If one of the T constructors threw, then any T objects that were fully constructed were properly destroyed and, finally, operator delete was automatically called to release the memory. That makes us leakproof.
My understanding was that if a constructor throws an exception, the application should cleanup any allocated resources. How is the above leakproof?
Quoting the C++03 standard, §5.3.4/8:
§5.3.4/17:
Consequently, if any
Tconstructor throws an exception, the runtime will destroy any already-created subobjects of theTinstance whose constructor threw, then calloperator delete[]on the array as a whole, destroying any already-created elements and deallocating the array’s memory.