指针变量和引用变量之间的区别是什么?


当前回答

我对引用和指针有一个类比,将引用看作对象的另一个名称,将指针看作对象的地址。

// receives an alias of an int, an address of an int and an int value
public void my_function(int& a,int* b,int c){
    int d = 1; // declares an integer named d
    int &e = d; // declares that e is an alias of d
    // using either d or e will yield the same result as d and e name the same object
    int *f = e; // invalid, you are trying to place an object in an address
    // imagine writting your name in an address field 
    int *g = f; // writes an address to an address
    g = &d; // &d means get me the address of the object named d you could also
    // use &e as it is an alias of d and write it on g, which is an address so it's ok
}

其他回答

除了语法糖,引用是常量指针(而不是指向常量的指针)。在声明引用变量时,必须确定它所指的内容,以后不能更改它。

更新:现在我再考虑一下,有一个重要的区别。

常量指针的目标可以通过获取其地址并使用常量转换来替换。

引用的目标不能以UB以外的任何方式替换。

这应该允许编译器对引用进行更多优化。

不能像指针一样取消引用,当取消引用时,

引用和指针都是通过地址工作的。。。

so

你可以这样做

int*val=0xDEADBEEF;*val是0xDEADBEEF的值。

你不能这样做int&V=1;

*不允许使用val。

指针和引用之间有一个根本的区别,我没有看到任何人提到过:引用支持函数参数中的引用传递语义。指针,虽然它最初不可见,但它不可见:它们只提供值传递语义。这在本文中得到了很好的描述。

当做&rzej公司

除非我需要以下任何一项,否则我会使用参考资料:

空指针可以用作哨兵价值,通常是一种廉价的方式避免函数重载或使用嘘声。你可以在指针上做算术。例如,p+=偏移量;

将指针视为名片:

它让你有机会联系某人它可以是empy它可能包含错误或过时的信息你不确定上面提到的某人还活着你不能直接与卡片通话,你只能用它打电话给某人也许有很多这样的卡片

将推荐人视为与某人的主动通话:

你很确定你联系过的人还活着您可以直接通话,无需额外通话你很确定你不会和一个空地方或一块垃圾说话你不能确定你是唯一一个当前正在与此对象交谈的人