开发者

c++ reference/pointer [duplicate]

This question already has answers here: Closed 12 years ago.

Possible开发者_如何学C Duplicate:

Difference between pointer variable and reference variable in C++

I saw this simple code the other day, and I consider myself a beginner with pointers, although I have about a year and half experience with c++. Anyways...

Whats the difference between

int a = 0; 
int &b = a; 

and

int a = 0
int *p = &a; 

Obviously, p holds the address of a, but b is a reference to a, meaning I can change the value of a with b. But I can also do the same thing with p. So what are advantages or disadvantages?


  • A reference must always be initialized
  • A reference can't be null
  • Once initialized, a reference can't be changed to be an alias of a different object.


I think it comes down to how you plan to use the variables afterwards in your program. Both statements appear to do the same thing (in this limited scope).

The first approach seems to be (in my opinion) poor programming practice since it may not be obvious later in the program that changing the value of b also changes the value of a. In the second, at least it is known that p is a pointer, so you should expect the side effects that come with changing the value to which it points.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜