FAQ 32.05 Is the reference-versus-pointer issue influenced by whether or not the object is allocated from the heap?

graphics/new_icon.gif

No, there is very little relationship between these issues.

Occasionally, the claim is made that if an object is allocated via new then it should be passed via pointer; otherwise it should be passed by reference. This is not correct. There are two separate questions, when to delete the object and how to pass it.

First consider the issue of deleting the object. If an object is allocated from the heap (e.g., p = new Fred();), then some routine has to be responsible for deleting it (e.g., delete p;), and the routine must have a pointer (e.g., p) to it. There are three common situations.

  1. The routine responsible for deleting the object is the same routine that created it, in which case a local auto_ptr is the easy solution: e.g., auto_ptr<Fred> p(new Fred());

  2. The routine responsible for deleting the object is the destructor of the same object that created the object. In this case put an auto_ptr in the this object and define a copy constructor and assignment operator that allocate a copy of the object from the heap (see FAQ 30.12).

  3. There is no clear responsibility for the delete, but the newed object should be deleted when there are no pointers to it. In this case, use reference counting and avoid passing raw pointers to the object. (See FAQ 31.09.)

Now consider how the object should be passed. Assume that the routine f() takes a Fred object. Which is better, f(Fred* p) or f(Fred& r)? The key criterion is this: Does f() want to handle the case when it gets passed a nonobject (that is, the NULL pointer)? If it does, then the pointer form is indicated because it can use NULL to indicate the nonobject case. If f() always needs an actual Fred object, then the best way to signal this is to use a reference, which guarantees that it can't be passed a NULL since a reference can't legally be NULL.

Notice that the issues of deletion and passing are almost completely independent. Obviously, if reference counting is used to handle the deletion problem, then pointer-like objects are typical. But otherwise the questions aren't related. References can be used even if the object was allocated off the heap, and pointers can be used even if the object was not allocated from the heap, since it is always possible to have a pointer to a local or global object (so long as the object outlives the pointer to it).



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