FAQ 32.04 How should pointers across block boundaries be controlled?

Avoid storing the address of a local object created in an inner scope in a pointer in an outer scope. Here's an example.

 class Fred { public:   void method() throw(); }; void doSomething(Fred& x) throw(); void f() {   Fred* p;   {     Fred a;     p = &a;                                          <-- 1   }   doSomething(*p);                                   <-- 2   p->method();                                       <-- 3 } 

(1) Suspicious...

(2) Bang!

(3) Bang!

When control flow leaves the inner block, a will be destroyed and p will be pointing at garbage. Because control can leave the inner scope a number of different ways (including an uncaught exception), setting the outer scope's pointer to point to an inner scope's object can lead to subtle errors and should be avoided on principle.

If the address of an inner scope's object has to be stored in an outer scope's pointer, then the outer scope's pointer should be changed to NULL (or some other safe value) before leaving the inner scope. Generally speaking, you should guarantee that the pointer is set to NULL by creating a pointer-like class whose destructor sets the pointer to NULL, then replace the Fred* local variable with a local object of that class.

Note that the problem addressed by this FAQ can occur only with pointers, not with references. This is because a reference is permanently bound to its referent at the moment it is initialized. This is yet another reason to prefer references to pointers (see FAQ 11.09).



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