Thursday, March 13, 2008

References in favor of pointers use

Always try to use reference instead of pointer to data wherever is possible.
A pointer to a data always raises the question if the pointer holds valid data, if it's 0 (NULL) for instance.
A reference shows that an object is passed and we don't do any data validation anymore, as for pointers.

// foo needs an instance of Foo
void foo(Foo* pF)
{
_ASSERTE(pF != 0);
....
}

// foo needs an instance of Foo
void foo(Foo& f)
{
....
}

It makes code writing and reading easier.

Using pointer variable is necessarily though in some situations.
You might want an optional parameter to your method:

// foo does NOT need an instance of Foo
void foo(Foo* pF)
{
if(pf != 0)
{
// use Foo object
....
}
else
{
// do something else in absence of a Foo object
...
}
}


This coding style and other good ones are mentioned in the paper http://www.research.att.com/~bs/JSF-AV-rules.pdf
The paper is mentioned on the home page of the father of C++.

No comments: