Nick said:
There is a difference - the pointer can be set to 0 and subsequently tested.
Indeed it is common to write stuff like:
if( !p ) p = new P();
There is no equivalent for references.
That's not what the OP was doing. References and pointers are *not* the
same thing; however, I know of no problem with binding *new to a
reference, and your example does not demonstrate one. It only shows a
pointer being used in a way that a reference cannot. Often, references
make more sense than pointers for this sort of thing. For example, it
is common to have a member pointer to some memory allocated by the
constructor. In this case, the memory typically is deallocated in the
destructor, and there is no point in resetting the pointer to null. In
fact, I find references preferable to pointers in this case, since you
will get a compile-time error if you forget to allocate the memory. If
you forget to initialize the pointer, the error will not occur until
run-time; such bugs can be horribly pernicious.
The advantage of references is the gaurantee (in the absence of people dong
the above) that the reference is valid.
There is no such guarantee.
This is very helpful when dealing with analy retentive coding standards that
insist that you check all pointers for null on entry.
Blame the coding standard, not the initialiation of references with
dynamically allocated memory.
One advantage of pointers is that you can put them in an auto_ptr and forget
them. (Of course you could write an equivalent for your references).
Another is that you can use 0 to mean something - either as a parameter when
it usualy means 'use defaults' or as a member when it means 'not yet
initialized'
Yes, pointers certainly have the advantage over references in many (but
not all) cases.
I have found a more serious argument: consider
AnyClass& reg=*new DerivedFromAnyClass();
The standard states that the implementation can (implementation defined)
bind to the AnyClass subobject of a temporary copy.
This would obviously be a disaster since the original would leak and delete
® would try to deallocate something on the stack.
Only if the destructor is non-virtual. The same argument can be made
against pointers. This is not a reference-specific problem.
P.S. The equivalent to
AnyClass& reg=*new AnyClass();
is
AnyClass * const pReg=new AnyClass();
not
AnyClass *pReg=new AnyClass();
Because the latter can be rebound unlike the reference
Again, the OP was not looking to "rebind the reference." You've
mentioned cases where pointers are needed. If your point is that
references cannot entirely replace pointers, I wholeheartedly agree.
However, I still see nothing wrong with either of the OP's offerings.
-Jeff