2008-03-25

Changed my mind: reference params are better than pointer params

Confession: for long time, I've been thinking that C++ reference is a fancy and a completely stupid way of writing a pointer. A way useful only for two things. One is operator overloading when an lvalue is needed - i.e. where "&a += c" semantics is not an acceptable way of writing "a+=c". The second thing is to make it easier to cut-and-paste code across functions, so that a lazy programmer wouldn't have hard time adding all those stars. The truth is different: reference is a significantly different language tool than a pointer. A reference can never be invalid, at least unless forced to be so with a far less-trivial construct than what is needed to make a pointer invalid.

In the modern era of C++ references and boost::shared_ptr, pointers can really be confined to something that is "explicitly nullable" and where you need this nullability.

VZ: "But of course. Every * and -> is an access violation waiting to happen"

3 comments:

kuchin said...

Check out Python ;)

artyom said...

> A reference can never be invalid

It can be invalid in the same way
the pointer can be. The only diffrerence you can't check it explictly like you can in case of pointer.

I mean you can always write

assert(pointer!=NULL)

If you are paranoid.

Better thing is that they can't have undefined state like pointers (NULL).

The best thing about reference
is actually syntactic sugar. especially with operators overloading -- see and example of vector or map.

Pavel Radzivilovsky said...

You can check a reference for null:

assert(&reference);

But the story is that it's goddamn hard to produce a null reference. The only way to do it is initialize a reference by dereferencing a null pointer. It's there where an assertion (or actually, a release-time check) should take place.