The goal is to make the code exception safe, that is, safe in the presence of exceptions (see FAQ 9.03). As a pleasant side effect, it becomes unnecessary to remember (and therefore, in a sense, impossible to forget) to make sure that the temporary object is deleted. Using a managed pointer (for example, an auto_ptr<T>) meets these goals since the managed pointer's destructor automatically deletes the temporary object. Here's an example. #include <new> #include <iostream> #include <memory> using namespace std; class Fred { public: ~Fred() throw(); }; Fred::~Fred() throw() { cout << "Fred dtor\n"; } void sample() throw(bad_alloc) { auto_ptr<Fred> ptr( new Fred() ); if (rand() % 2) { cout << "randomly doing an 'early return'\n"; return; } cout << "randomly NOT doing an 'early return'\n"; <-- 1 } int main() { sample(); }
|