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.
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). |