参考与指针

Que*_*est 13 c++ pointers reference

有什么不同?因为这:

int Value = 50;
int *pValue = &Value;

*pValue = 88;
Run Code Online (Sandbox Code Playgroud)

和ref版本做同样的事情:

int Value = 50;
int &rValue = Value;

rValue = 88;
Run Code Online (Sandbox Code Playgroud)

哪一个更好用?谢谢.

Lig*_*ica 20

在这种情况下,它们是等价的.

你使用哪个并不重要,也不是"最好的".

如果你真的想在它们之间做出选择,那么参考可能更具惯用性.我总是坚持参考,因为我的OCD喜欢它:他们感觉"更紧",不能重新绑定(无论你有没有注意到),并且不需要取消引用来获得价值.

但是我不知道在这个问题上对这个问题有任何普遍的共识.

另请注意,如果您的实现没有使用指针实现引用,则两者可能无法编译为相同的代码,但我知道没有这样的实现,并且您无论如何都不会注意到差异.

  • @Quest:还有其他一些,但也有一些情况,使用指针是有效的,并且使用引用不是,例如,如果您尝试将句柄重新绑定到不同的`int`,或者如果您想要保持"null"句柄,或者等等.当人们询问指针与引用时,我尽量不做一般化. (2认同)

Jef*_*mas 18

指针是内存位置的地址.您可以将该地址的值更改为指向不同的内存地址.

引用是变量的别名.您只能在声明期间分配此别名.您无法更改引用声明之后别名的变量.


引用无法进行以下指针赋值.

int a = 10;
int b = 20;

int* pInt = NULL; // A pointer pointing at nothing.
pInt = &a; // pInt now points at a
pInt = &b; // pInt now points at b
Run Code Online (Sandbox Code Playgroud)

至于哪一个更好,这一切都取决于背景.

我使用方法和函数参数的引用.

void updateFoo(Foo& foo)
Run Code Online (Sandbox Code Playgroud)

我使用别名复杂对象的引用.

Foo& foo = bar.getBaz().getFoo(); // easy access to foo
Run Code Online (Sandbox Code Playgroud)

我使用指针来动态分配对象.

Foo* pFoo = new Foo();
Run Code Online (Sandbox Code Playgroud)

我使用指针指向可能指向不同值的事物(根本不包括任何值).

Foo* pFoo = NULL;

if (condition1)
    pFoo = &foo1;
else (condition2)
    pFoo = &foo2;
Run Code Online (Sandbox Code Playgroud)

作为一般规则,我默认引用并在引用限制导致问题的地方使用指针.


Dor*_*rin 11

不同之处是:

Reference是对象的别名,并且与对象具有相同的地址.

int a;         //  address of   a : 0x0012AB
int &ref = a;  //  address of ref : 0x0012AB (the same)
Run Code Online (Sandbox Code Playgroud)

必须初始化参考:

int &ref = a; // GOOD, is compiling
int &ref;     // BAd, is not compiling
Run Code Online (Sandbox Code Playgroud)

指针是另一个包含地址的变量:

int a = 5;     //  address of a : 0x0012AB 
int *p = &a;   //  address of p : 0x0012AF (is different )

// value of a is 5
// value of p is 0x0012AB  (address of a)
Run Code Online (Sandbox Code Playgroud)

指针可以为NULL

int *p = NULL;
Run Code Online (Sandbox Code Playgroud)