reference Vs. pointer

  1. pointer Vs. reference
  2. References

pointer Vs. reference

Firstly, reference is the concept of C++, it is a simple reference data type that is less powerful but safer than the pointer type.

int a=2;
int& ra=a; // define a reference ra
std::cout << ra; // 2

Reference is a sort of alias for the target. For example, ra is a sort of alias for the r in the above example. When we refer to the ra, practically refer to the a. ra and a are conceptually one. Changing ra means changing a, and changing a means changing ra.

Essentially, reference is same as the pointer, reference is the grammar sugar of the pointer.

Because from the assembly code, the implementation of reference is almost same as pointer. Therefore, reference is also need to be allocated the memory.

  • Reference is the grammar sugar of the pointer, it is intended as the const pointer which can do the address-of operation(&) and the dereference operation(*) by the compiler.
  • Reference must be initialized when it is created, pointer not.
  • Reference is a sort of alias of the target, therefore, reference must be non-null, pointer not.
  • Reference is the target value execute the increment(++) or decrement(--) operation, but the pointer is itself executes the increment or decrement operation.

Particularly, the reference can be used as the formal parameter to avoid the check of if the passed parameter is 0. For example:

void fun1(int *point)
{
    // need to check whether the point is NULL
     if(!point)
     {
        return;
     }
}

void fun2(int &reference)
{
     // reference is must be non-null 
}

sizeof(*pointer) will get the memory space of a pointer, sizeof(&reference) will get the referenced object’s memory space.

References


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 gzrjzcx@qq.com

文章标题:reference Vs. pointer

文章字数:289

本文作者:Alex Zou

发布时间:2019-02-22, 23:44:05

最后更新:2024-07-10, 03:02:36

原始链接:https://www.hellscript.cc/2019/02/22/subposts_c/reference-Vs-pointer/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

有钱的捧个钱场,没钱的借钱也捧个钱场