Talk:Reference (C++)

From Wikipedia, the free encyclopedia

"In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C, which is a reference in the general sense but not in the sense used by C++." huh???? —Preceding unsigned comment added by 67.188.227.244 (talk • contribs) 07:01, 16 June 2006

A "pointer" in C++ is a reference (computer science); but is never called that in C++. --Spoon! 08:44, 18 October 2007 (UTC)


I've deleted a section labelled "not true" which I mostly wrote, which was based on a mistaken idea of mine. --Shyland 11:55, 6 January 2007 (UTC)

[edit] Invalid References

The text states:

a reference only becomes invalid in two cases:
  • If it refers to an object with automatic allocation which goes out of scope,
  • If it refers to an object inside a block of dynamic memory which has been freed.

Not true.

int * x = 0 ;
int & y = * x ;

creating a "null" reference of sorts -- its a reference to the memory at address 0 interpeted as an "int". --BostonMA talk 01:30, 17 July 2007 (UTC)

That ought to cause a segfault on initialisation, right? So the reference doesn't become invalid, it never becomes anything at all =) —Preceding unsigned comment added by 81.216.240.6 (talk) 08:53, 17 October 2007 (UTC)
Not in most compilers. Since a reference is an address and the pointer is an address, the initialization just assigns the address of the pointer to the reference (how else would you do it?); no dereferencing is needed, and hence no segmentation fault. Most compilers represent l-values (e.g. the dereferencing of a pointer) as references anyway. --Spoon! (talk) 22:48, 25 March 2008 (UTC)

---

I'm not sure if these results are valid for all compilers, nor am I sure what the C++ specification says, but:

#include <stdio.h>

int main(int argc, char *argv[]) {
    int * x = 0;
    int & y = *x;

    fprintf(stderr, "&y = ");
    fprintf(stderr, "%d\n", &y);
    fprintf(stderr, "y  = ");
    fprintf(stderr, "%d\n", y);
}

Produces this output:

&y = 0
y  = Segmentation fault (core dumped)

At least on modern versions of GCC, references can be null and won't SEGV until you use them. This is consistent with my understanding of how references might be implemented. I believe that BostonMA is correct. TSawyer 70.101.133.253 (talk) 01:31, 2 January 2008 (UTC)

[edit] More questions

The article says this is the standard layout for a reference declaration:

<Type> & <Name>

But I think the following three examples are all the same:

int& rA = A;
int & rA = A;
int &rA = A;

Am I correct?

Also: I think I'd be good if the article pointed out the differences between the different uses of "&" in the context of addresses: either it is the "address-of operator" or the "reference datatype token". --Abdull (talk) 11:25, 9 February 2008 (UTC)