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:
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.
No Comments/Pingbacks for this post yet...
Comments are closed for this post.
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.
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 |