FAQ 31.08 What should be done with a pointer to an object that is allocated and deallocated in the same scope?

graphics/new_icon.gif

It should be placed in a managed pointer object that is local to the scope.

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(); } 

(1) In either case, we do NOT say delete ptr, since ptr is a managed pointer



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net