Play and learn 300 000+ tabs online

Wednesday, June 2, 2010

Pointers Differed from References

Pointers may be null.

References may not be null.

Say you are writing a function and you know that you do not wish an argument to be an object of type T.

That leaves you with two choices. The argument can be a pointer to T or a reference to T.

If it is acceptable for the caller of the function to pass nothing, either because he has nothing or because nothing can be used to indicate special processing, then use a pointer because it can be initialized with a null value.

If it is not acceptable for the caller of the function to pass nothing, then use a reference because it cannot be initialized with a null value.

Enforce contracts at compile-time rather than at run-time wherever possible.

I have been looking at another object-oriented programming language as of late and one of the things I don't like about it is that it only allows access to objects through its version of references in a world where a reference can always refer to nothing. Thus much of the code I have seen is littered with statements such as (if ref!=null) or the code just throws exceptions at run-time if a null reference is used.

IMHO the C++ methods for accessing objects indirectly are more diverse than this other language and the slight difference between pointers and references in C++ allow the programmer to communicate intent to fellow programmers with
the advantage of support of the compiler.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.