Why are pointers to a reference illegal in C++?

前端 未结 5 1750
悲&欢浪女
悲&欢浪女 2020-12-04 14:50

As the title itself mentions - why are pointer to a reference illegal, while the reverse is legal in C++?

5条回答
  •  情歌与酒
    2020-12-04 15:08

    A pointer needs to point to an object. A reference is not an object.

    If you have a reference r, once it is initialized, any time you use r you are actually using the object to which the reference refers.

    Because of this, you can't take the address of a reference to be able to get a pointer to it in the first place. Consider the following code:

    int x;
    int& rx = x;
    
    int* px = ℞
    

    In the last line, &rx takes the address of the object referred to by rx, so it's exactly the same as if you had said &x.

提交回复
热议问题