Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

c++ - What does int & mean

A C++ question,

I know

int* foo(void)

foo will return a pointer to int type

how about

int &foo(void)

what does it return?

Thank a lot!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It returns a reference to an int. References are similar to pointers but with some important distinctions. I'd recommend you read up on the differences between pointers, references, objects and primitive data types.

"Effective C++" and "More Effective C++" (both by Scott Meyers) have some good descriptions of the differences and when to use pointers vs references.

EDIT: There are a number of answers saying things along the lines of "references are just syntactic sugar for easier handling of pointers". They most certainly are not.

Consider the following code:

int a = 3;
int b = 4;
int* pointerToA = &a;
int* pointerToB = &b;
int* p = pointerToA;
p = pointerToB;
printf("%d %d %d
", a, b, *p); // Prints 3 4 4
int& referenceToA = a;
int& referenceToB = b;
int& r = referenceToA;
r = referenceToB;
printf("%d %d %d
", a, b, r); // Prints 4 4 4

The line p = pointerToB changes the value of p, i.e. it now points to a different piece of memory.

r = referenceToB does something completely different: it assigns the value of b to where the value of a used to be. It does not change r at all. r is still a reference to the same piece of memory.

The difference is subtle but very important.

If you still think that references are just syntactic sugar for pointer handling then please read Scott Meyers' books. He can explain the difference much better than I can.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...