Home
Fractals
Tutorials
Books
My blog
My LinkedIn Profile

BOOKS i'm reading

Napoleon Hill Keys to Success: The 17 Principles of Personal Achievement, Napoleon Hill, ISBN: 978-0452272811
The 4-Hour Workweek: Escape 9-5, Live Anywhere, and Join the New Rich (Expanded and Updated), Timothy Ferriss, ISBN: 978-0307465351
The Fountainhead, Ayn Rand, ISBN: 0452273331
Web Hosting Canada

mailto:olivier@olivierlanglois.net

Using references or pointers for function arguments

10/06/07

Permalink 12:11:35 am, by lano1106, 260 words, 1585 views   English (CA)
Categories: C++

Using references or pointers for function arguments

Which is better

void f(int &a);

or

void f(int *a);

?

Once compiled, there should not be any difference between the 2 versions as references are most likely implemented with pointers under the compiler hood. The main difference between passing a pointer to a function vs a reference is that with the reference you are sure that the reference points to a valid object where as with pointers you could pass a NULL pointer.

Hence, if a NULL pointer is not a valid value for a function, you can enforce that fact by passing a reference. Some people argue that it is possible to have dangling references by doing:

int &f()
{
    int a;
    a = 5;
    return a;
}

int main(int argc, char *argv)
{
    int &r = f();
    return 0;
}

or

int main(int argc, char *argv)
{
    int *p = new int(5);
    int &r = *p;
    delete p;
    return 0;
}

but I consider these cases pathological and my opinion is that references are safer than pointers because:

  1. They behave like const pointers.
  2. They must be initialized at their declaration.

With these, it should be much harder to have *unintentionally* dangling references than having uninitialized pointers especially if you do not do the newbie mistake of returning a reference to a local variable. My C++ debugging experience has led to me to fix plenty of pointer problems but I have never seen until now a dangling reference problem in real code.

Also, Scott Meyers, in his book More Effective C++ (item 1: Distinguish between pointers and references), goes in the same way about this issue.

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Comments are closed for this post.

Olivier Langlois's blog

I want you to find in this blog informations about C++ programming that I had a hard time to find in the first place on the web.

October 2024
Sun Mon Tue Wed Thu Fri Sat
 << <   > >>
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31    

Search

Custom Search

Misc

XML Feeds

What is RSS?

Who's Online?

  • Guest Users: 19

powered by
b2evolution