简体   繁体   English

参考与指针

[英]Reference vs. pointer

What is the difference? 有什么不同? Because this: 因为这:

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

*pValue = 88;

and ref version do the same: 和ref版本执行相同的操作:

int Value = 50;
int &rValue = Value;

rValue = 88;

Which one is better to use? 哪个更好用? Thanks. 谢谢。

In this case, they are equivalent. 在这种情况下,它们是等效的。

It does not matter which you use, and neither is "best". 不管使用哪个,都不是“最佳”。

If you really want to choose between them then the reference is probably more idiomatic. 如果您真的想在它们之间进行选择,则参考可能更惯用。 I generally stick to references wherever I can because my OCD likes it: they feel "tighter", cannot be re-bound (with or without you noticing) and don't require a dereference to get to the value. 我通常会在任何可能的地方坚持引用,因为我的OCD会喜欢它:它们感到“更紧”,无法重新绑定(无论是否注意到),也不需要取消引用即可获取该值。

But I'm not aware of any general consensus on the issue for cases such as this. 但是我不知道在这种情况下对此问题有任何普遍共识。

Also note that the two may not compile to the same code if your implementation does not implement references with pointers, though I know of no implementation like that, and you wouldn't notice the difference anyway. 另请注意,如果您的实现未实现带有指针的引用,则两者可能不会编译为同一代码,尽管我不知道类似的实现,而且您也不会注意到两者之间的区别。

A pointer is the address of the memory location. 指针是存储位置的地址。 You can change the value of that address to point at different memory addresses. 您可以更改该地址的值以指向不同的内存地址。

A reference is an alias of the variable. 引用是变量的别名。 You can only assign this alias during declaration. 您只能在声明期间分配此别名。 You cannot change which variable the reference is an alias of after it's declared. 在声明引用后,您不能更改引用是别名的变量。


The following pointer assignments are not possible with references. 以下指针分配不能用于引用。

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

As for which one is better, it all depends on context. 至于哪种更好,则完全取决于上下文。

I use references for method and function parameters. 我将引用用于方法和函数参数。

void updateFoo(Foo& foo)

I use references to alias complex objects. 我使用引用来别名复杂对象。

Foo& foo = bar.getBaz().getFoo(); // easy access to foo

I use pointers for dynamically allocated objects. 我将指针用于动态分配的对象。

Foo* pFoo = new Foo();

I use pointers for things which may point at different values (including no value at all). 对于可能指向不同值(包括完全没有值)的东西,我使用了指针。

Foo* pFoo = NULL;

if (condition1)
    pFoo = &foo1;
else (condition2)
    pFoo = &foo2;

As a general rule, I default to references and use pointers in places where the limitations on references cause problems. 通常,我默认使用引用,并在对引用的限制导致问题的地方使用指针。

The differences are: 不同之处在于:

Reference is an alias of an object and has the same address as the object. 引用是对象的别名,并且具有与对象相同的地址。

int a;         //  address of   a : 0x0012AB
int &ref = a;  //  address of ref : 0x0012AB (the same)

References must be initialized : 引用必须初始化

int &ref = a; // GOOD, is compiling
int &ref;     // BAd, is not compiling

Pointer is another variable that holds an address: 指针是另一个保存地址的变量:

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)

Pointers can be NULL 指针可以为NULL

int *p = NULL;

My rule of thumb is to favor using a reference or const reference, unless a pointer is required. 我的经验法则是倾向于使用引用或const引用,除非需要使用指针。

The reference may not be reseated, and it is syntactically cleaner. 该引用可能无法重新使用,并且在语法上更干净。 The reference also guarantees to you that the reference is not NULL . 该引用还向您保证该引用不是NULL

I may also use a pointer for convenience when using arrays. 为了方便使用数组,我也可以使用指针。

I agree with justin's answer and would like to clarify it with the tiniest example. 我同意贾斯汀的回答,并希望以最小的例子来澄清它。

Suppose you don't quite remember the syntax of a 2D image geometric library: is it 假设您不太记得2D图像几何库的语法:是吗

bool BooleanOr( const Bitmap & input1, const Bitmap & input2, Bitmap * output );

or is it 还是

bool BooleanOr( Bitmap * output, const Bitmap & input1, const Bitmap & input2 );

If in your company everybody uses pointers for outputs and const references for inputs it's virtually impossible to make a mistake: when you see calls such as 如果在您的公司中每个人都使用指针作为输出,而const引用作为输入,则几乎不可能犯错:当您看到诸如

BooleanOr( thisBitmap, thatBitmap, & anotherBitmap ); BooleanOr(thisBitmap,thatBitmap和anotherBitmap);

you immediately know the syntax. 您立即知道语法。

Great answers here. 很好的答案。 I would like to point out 2 specific usages of references:- 我想指出参考的2种具体用法:

Case 1: While implementing operator[] . 情况1:在实现operator[] This operator typically needs to return something that can be used as the target of an assignment Example:- 该操作员通常需要返回的东西 ,可以被用作分配的目标 : -

vector<int> v(20);
v[1] = 5; //The target of the assignment is the return value of operator []

Here the operator [] returns a reference of the element at the specified index in the vector . 这里的operator []返回vector指定索引处元素的引用 Had operator [] been designed to return a pointer to the element at the specified index the 2nd line would have to be written like this:- 如果将operator []设计为返回指向指定索引处的元素的指针 ,则第二行必须这样编写:-

*v[1] = 5

Now that makes v look like it's a vector of pointers - which it's definitely not!! 现在,使v看起来像是指针的向量-绝对不是! Thus for sanity to prevail - the operator [] returns a reference and not a pointer to the indexed element in the vector 因此,为了保持理智, operator []返回一个引用,而不是指向向量中索引元素的指针

Case 2: No explicit null check required for references. 情况2:引用不需要显式的null检查。 Some answers have already talked about it - wanted to present the advantage using a code snippet:- 一些答案已经讨论过了-想要使用代码片段来展示其优势:-

void fun(const int& val)
{
  cout << val;
}

void fun(const int* val)
{
  if (val){ //Additional overhead with pointers
    cout << *val;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM