[英]Reference vs. pointer
有什么不同? 因为这:
int Value = 50;
int *pValue = &Value;
*pValue = 88;
和ref版本执行相同的操作:
int Value = 50;
int &rValue = Value;
rValue = 88;
哪个更好用? 谢谢。
在这种情况下,它们是等效的。
不管使用哪个,都不是“最佳”。
如果您真的想在它们之间进行选择,则参考可能更惯用。 我通常会在任何可能的地方坚持引用,因为我的OCD会喜欢它:它们感到“更紧”,无法重新绑定(无论是否注意到),也不需要取消引用即可获取该值。
但是我不知道在这种情况下对此问题有任何普遍共识。
另请注意,如果您的实现未实现带有指针的引用,则两者可能不会编译为同一代码,尽管我不知道类似的实现,而且您也不会注意到两者之间的区别。
指针是存储位置的地址。 您可以更改该地址的值以指向不同的内存地址。
引用是变量的别名。 您只能在声明期间分配此别名。 在声明引用后,您不能更改引用是别名的变量。
以下指针分配不能用于引用。
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
至于哪种更好,则完全取决于上下文。
我将引用用于方法和函数参数。
void updateFoo(Foo& foo)
我使用引用来别名复杂对象。
Foo& foo = bar.getBaz().getFoo(); // easy access to foo
我将指针用于动态分配的对象。
Foo* pFoo = new Foo();
对于可能指向不同值(包括完全没有值)的东西,我使用了指针。
Foo* pFoo = NULL;
if (condition1)
pFoo = &foo1;
else (condition2)
pFoo = &foo2;
通常,我默认使用引用,并在对引用的限制导致问题的地方使用指针。
不同之处在于:
引用是对象的别名,并且具有与对象相同的地址。
int a; // address of a : 0x0012AB
int &ref = a; // address of ref : 0x0012AB (the same)
引用必须初始化 :
int &ref = a; // GOOD, is compiling
int &ref; // BAd, is not compiling
指针是另一个保存地址的变量:
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)
指针可以为NULL
int *p = NULL;
我的经验法则是倾向于使用引用或const引用,除非需要使用指针。
该引用可能无法重新使用,并且在语法上更干净。 该引用还向您保证该引用不是NULL
。
为了方便使用数组,我也可以使用指针。
我同意贾斯汀的回答,并希望以最小的例子来澄清它。
假设您不太记得2D图像几何库的语法:是吗
bool BooleanOr( const Bitmap & input1, const Bitmap & input2, Bitmap * output );
还是
bool BooleanOr( Bitmap * output, const Bitmap & input1, const Bitmap & input2 );
如果在您的公司中每个人都使用指针作为输出,而const引用作为输入,则几乎不可能犯错:当您看到诸如
BooleanOr(thisBitmap,thatBitmap和anotherBitmap);
您立即知道语法。
很好的答案。 我想指出参考的2种具体用法:
情况1:在实现operator[]
。 该操作员通常需要返回的东西 ,可以被用作分配例的目标 : -
vector<int> v(20);
v[1] = 5; //The target of the assignment is the return value of operator []
这里的operator []
返回vector
指定索引处元素的引用 。 如果将operator []
设计为返回指向指定索引处的元素的指针 ,则第二行必须这样编写:-
*v[1] = 5
现在,使v
看起来像是指针的向量-绝对不是! 因此,为了保持理智, operator []
返回一个引用,而不是指向向量中索引元素的指针
情况2:引用不需要显式的null
检查。 一些答案已经讨论过了-想要使用代码片段来展示其优势:-
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.