Question:

I know references are syntactic sugar, so code is easier to read and write.

But what are the differences?


Summary from answers and links below:

  1. A pointer can be re-assigned any number of times while a reference can not be re-seated after binding.
  2. Pointers can point nowhere (NULL),
    whereas reference always refer to an object.
  3. You can't take the address of a reference like you can with pointers.
  4. There's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj
    + 5
    ).

To clarify a misconception:

The C++ standard is very careful to avoid dictating how a compiler must implement references, but every C++ compiler implements references as pointers. That is, a declaration such as:

int &ri = i;

if it's not optimized away entirely, allocates
the same amount of storage as a pointer, and places the address of i into that storage.

So, a pointer and a reference both occupy the same amount of memory.

As a general rule,

  • Use references in function parameters and return types to define useful and self-documenting interfaces.
  • Use pointers to implement algorithms and data structures.

Interesting read:

Answer:

  1. A pointer can be re-assigned:

    int x = 5;
    int y = 6;
    int *p;
    p = &x;
    p = &y;
    *p = 10;
    assert(x == 5);
    assert(y == 10);

    A reference cannot, and must be assigned at initialization:

    int x = 5;
    int y = 6;
    int &r = x;
  2. A pointer has its own memory address and size on the stack (4 bytes on x86), whereas a reference shares the same memory address (with the original variable) but also takes up some space on the stack. Since a reference has the same address as the original variable
    itself, it is safe to think of a reference as another name for the same variable. Note: What a pointer points to can be on the stack or heap. Ditto a reference. My claim in this statement is not that a pointer must point to the stack. A pointer is just a variable
    that holds a memory address. This variable is on the stack. Since a reference has its own space on the stack, and since the address is the same as the variable it references. More on stack
    vs heap
    . This implies that there is a real address of a reference that the compiler will not tell you.

    int x = 0;
    int &r = x;
    int *p = &x;
    int *p2 = &r;
    assert(p == p2);
  3. You can have pointers to pointers to pointers offering extra levels of indirection. Whereas references only offer one level of indirection.

    int x = 0;
    int y = 0;
    int *p = &x;
    int *q = &y;
    int **pp = &p;
    pp = &q;//*pp = q
    **pp = 4;
    assert(y == 4);
    assert(x == 0);
  4. Pointer can be assigned NULL directly, whereas reference cannot. If you try hard enough, and you know how, you can make the address of a reference NULL. Likewise, if you try hard enough you can have a reference to a pointer, and then that reference can contain
    NULL.

    int *p = NULL;
    int &r = NULL; <--- compiling error
  5. Pointers can iterate over an array, you can use ++ to
    go to the next item that a pointer is pointing to, and +
    4
     to go to the 5th element. This is no matter what size the object is that the pointer points to.

  6. A pointer needs to be dereferenced with * to
    access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to
    access it's members whereas a reference uses a ..

  7. A pointer is a variable that holds a memory address. Regardless of how a reference is implemented, a reference has the same memory address as the item it references.

  8. References cannot be stuffed into an array, whereas pointers can be (Mentioned by user @litb)

  9. Const references can be bound to temporaries. Pointers cannot (not without some indirection):

    const int &x = int(12); //legal C++
    int *y = &int(12); //illegal to dereference a temporary.

    This makes const& safer
    for use in argument lists and so forth.

What are the differences between a pointer variable and a reference variable in C++?的更多相关文章

  1. Route pattern cannot reference variable name more than once

    在用 Laravel Backpack 写一个定制化的 CRUD 页面.例如,一个指定店铺所拥有的商品的 CRUD 页面. 起初路由我是这样写的 CRUD::resource('products-of ...

  2. 【RF库测试】Variable Should not Exist & variable should exist

    Variable Should not Exist variable should exist

  3. differences between null pointer and void pointer.

    These are two different concepts, you cannot compare them. What the difference between the skunk and ...

  4. The difference between a local variable and a member variable

    package com.itheima_04; /* * 成员变量和局部变量的区别: * A:在类中的位置不同 * 成员变量:类中,方法外 * 局部变量:方法中或者方法声明上(形式参数) * B:在内 ...

  5. 【TensorFlow】TensorFlow获取Variable值,将Variable保存为list数据

    Variable类型对象不能直接输出,因为当前对象只是一个定义. 获取Variable中的浮点数需要从数据流图获取: initial = tf.truncated_normal([3,3], stdd ...

  6. Variable|quantitative variables|continuous variable|discrete variable|qualitative variables| observation|data set

    2.1Variables and Data Variable:某物或某人的某一特征和其他个体不同. quantitative variables:定量变量either discrete (可以被数)o ...

  7. Java Garbage Collection

    在C/C++中,需要自己负责object的creation 和 destruction. 如果忘记了destruction, 就容易出现OutOfMemoryErrors. Java中会有GC直接处理 ...

  8. A pointer is a variable whose value is the address of another variable 指针 null pointer 空指针 内存地址0 空指针检验

    小结: 1.指针的实际值为代表内存地址的16进制数: 2.不同指针的区别是他们指向的变量.常量的类型: https://www.tutorialspoint.com/cprogramming/c_po ...

  9. no pointer in java

    Why there are no pointers in Java? In Java there are references instead of pointers. These reference ...

随机推荐

  1. Visual C++.NET设计

    首先,创建对应的工程,VS2010以及以前的版本,创建项目时都可以在CLR下找到“Windows窗体应用程序”的项目模板,但是VS2012以后的版本就没这么方便了.可以通过打开旧版本的项目来修改,也可 ...

  2. Do More With These Great Plugins for Windows Live Writer(old)

    This article is out of day,now we use open live wirter, but we don’t have so much works great plugin ...

  3. NET Core微服务之路:再谈分布式系统中一致性问题分析

    前言 一致性:很多时候表现在IT系统中,通常在分布式系统中,必须(或最终)为多个节点的数据保持一致.世间万物,也有存在相同的特征或相似,比如儿时的双胞胎,一批工厂流水线的产品,当然,我们不去讨论非IT ...

  4. [Project] SpellCorrect源码详解

    该Project原来的应用场景是对电商网站中输入一个错误的商品名称进行智能纠错,比如iphoae纠错为iphone.以下介绍的这个版本对其作了简化,项目源代码地址参见我的github:https:// ...

  5. linux 下动态链接实现原理

    符号重定位 讲动态链接之前,得先说说符号重定位. c/c++ 程序的编译是以文件为单位进行的,因此每个 c/cpp 文件也叫作一个编译单元(translation unit), 源文件先是被编译成一个 ...

  6. GitHub 轻松提速教程

    通过修改hosts文件来提速,获取github的IP地址 访问:https://www.ipaddress.com/ 网址 依次获取以下三个网址的IP github.com github.global ...

  7. preg_match(): Compilation failed: character value in \x{} or \o{} is too large at offset 8

    如果用正则筛选中文的时候,需要在规则后面添加字符u,表示使用utf8编码去解析 $reg = '/[\x{4e00}-\x{9fa5}]/u'; 例如: $reg = '/[\x{4e00}-\x{9 ...

  8. 分布式控制系统Git学习

    git : n. 饭桶,无用的人 github : n. 社交编程及代码托管网站 hub: n. 中心:毂:木片 Git是一个分布式版本控制软件,最初由林纳斯·托瓦兹(Linus Torvalds)创 ...

  9. https网页加载http资源导致的页面报错及解决方案

    https是当下的网站的主流趋势,甚至像苹果这样的大公司,则完全要求用户必须使用https地址. 然而对于以前http链接来说,我们往往就存在一个兼容性问题,因为你不可能一下就全部切换过去,应该在很长 ...

  10. Windows.UI.Cred.dll损坏导致不能设置 PIN 密码

    心血来潮,重装系统. 然后发现不能设置 PIN,UWP界面在输完两个PIN后直接卡死(第一次设置的时候不需要输入第一行的PIN) google无果,打开系统日志,发现 上网下载一个对应版本的Windo ...