FAQ 2.11 What are the basics of passing objects by pointer?

graphics/new_icon.gif

Passing objects by pointer is not commonly used. The most common approaches are pass-by-reference and pass-by-auto_ptr. Pass-by-reference is used when the caller wants to retain ownership of the object (that is, when the caller wants to access the object after the call returns to the caller). Pass-by-auto_ptr is used when the caller wants to transfer ownership of the object to the called routine (that is, when the caller wants the object to get deleted before the called routine returns to the caller):

 #include <memory> using namespace std; #include "Car.hpp" typedef auto_ptr<Car> CarPtr; void f(Car& c) {   c.startEngine();   // ... }                                                    <-- 1 void g(CarPtr p) {   p->startEngine();   // ... }                                                    <-- 2 int main() {   CarPtr p(new Car());   f(*p);                                             <-- 3   g(p);                                              <-- 4 } 

(1) The Car object is not deleted at this line

(2) The Car object is deleted at this line

(3) Pass-by-reference; *p can be used after this line

(4) Pass-by-auto_ptr; *p cannot be used after this line

If the intent is for the caller to retain ownership of the object, pass-by-reference should generally be used. If the intent is for the ownership to be passed to the called routine, pass-by-auto_ptr should be used. About the only time pass-by-pointer should be used is when (1) the caller should retain ownership and (2) the called routine needs to handle "nothing was passed" (i.e., the NULL pointer) as a valid input. In the following example, note the explicit test to see if the pointer is NULL.

 #include <memory> using namespace std; #include "Car.hpp" typedef auto_ptr<Car> CarPtr; void h(Car* p) {   if (p == NULL) {     // ...   } else {     p->startEngine();     // ...   } }                                                    <-- 1 void i() {   h(NULL);                                           <-- 2   CarPtr p (new Car());   h(p.get());                                        <-- 3   // ... }                                                    <-- 4 

(1) As in pass-by-reference, the Car object is not deleted at this line

(2) NULL is a valid parameter to function h()

(3) Pass-by-pointer; *p can be used after this line

(4) The Car object is deleted at this line



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