#include // This object will create a buffer in constructor and delete // in destructor. As per RAII principle. // NOTE: if requested allocation is too bug the constructor will throw struct Buffer { char* buffer; int size; Buffer() : buffer(NULL) { buffer = 0; } Buffer(int sz) { size = sz; std::cerr << "allocate buffer of " << size << "\n"; buffer = new char[size]; } ~Buffer() { std::cerr << "free buffer of " << size << "\n"; delete [] buffer; } }; struct MultiBuffer { Buffer b1; Buffer b2; Buffer b3; // Constructor will initialize 3 objects which may throw // C++ language gaurantees that any successfully constructed // sub object will have its destructor called if the constructor // of the object throws an exception. MultiBuffer(int a, int b, int c) : b1(a), b2(b), b3(c) { } }; int main(int argc, char** argv) { try { MultiBuffer a(100,200,300); std::cerr << "allocation 1 success\n\n"; // The second Buffer object allocated in the constructor will throw // however the memory will be cleaned up for the first object so we // are good MultiBuffer b(500,2009999999,300); std::cerr << "allocation 1 success\n\n"; } catch(std::bad_alloc b) { std::cerr << "caught bad alloc\n\n"; } return 0; }