What are the differences between a pointer variable and a reference variable in C++?
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:
- A pointer can be re-assigned any number of times while a reference can not be re-seated after binding.
- Pointers can point nowhere (
NULL),
whereas reference always refer to an object. - You can't take the address of a reference like you can with pointers.
- 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:
- My alltime favorite C++ FQA lite.
- References vs. Pointers.
- An Introduction to References.
- References and const.
Answer:
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;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);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);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 errorPointers can iterate over an array, you can use
++to
go to the next item that a pointer is pointing to, and+to go to the 5th element. This is no matter what size the object is that the pointer points to.
4A 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..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.
References cannot be stuffed into an array, whereas pointers can be (Mentioned by user @litb)
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++?的更多相关文章
- Route pattern cannot reference variable name more than once
在用 Laravel Backpack 写一个定制化的 CRUD 页面.例如,一个指定店铺所拥有的商品的 CRUD 页面. 起初路由我是这样写的 CRUD::resource('products-of ...
- 【RF库测试】Variable Should not Exist & variable should exist
Variable Should not Exist variable should exist
- differences between null pointer and void pointer.
These are two different concepts, you cannot compare them. What the difference between the skunk and ...
- The difference between a local variable and a member variable
package com.itheima_04; /* * 成员变量和局部变量的区别: * A:在类中的位置不同 * 成员变量:类中,方法外 * 局部变量:方法中或者方法声明上(形式参数) * B:在内 ...
- 【TensorFlow】TensorFlow获取Variable值,将Variable保存为list数据
Variable类型对象不能直接输出,因为当前对象只是一个定义. 获取Variable中的浮点数需要从数据流图获取: initial = tf.truncated_normal([3,3], stdd ...
- Variable|quantitative variables|continuous variable|discrete variable|qualitative variables| observation|data set
2.1Variables and Data Variable:某物或某人的某一特征和其他个体不同. quantitative variables:定量变量either discrete (可以被数)o ...
- Java Garbage Collection
在C/C++中,需要自己负责object的creation 和 destruction. 如果忘记了destruction, 就容易出现OutOfMemoryErrors. Java中会有GC直接处理 ...
- 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 ...
- no pointer in java
Why there are no pointers in Java? In Java there are references instead of pointers. These reference ...
随机推荐
- 【repost】前端学习总结(二十三)——前端框架天下三分:Angular React 和 Vue的比较
目录(?)[+] 前端这几年的技术发展很快,细分下来,主要可以分成四个方面: 1.开发语言技术,主要是ES6&7,coffeescript,typescript等: 2.开发框架,如Ang ...
- 普通java程序,maven打包
pom.xml文件: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://ww ...
- 锚接口(下)——html5的history api
概述 虽然html5的history api是H5专门用来解决记录历史记录和单页面的方法,但是很多老式的浏览器并不支持它,所以一般遇到老式的浏览器会做一个polyfill使用之前的hashchange ...
- Javascript百学不厌 - 模块模式
记录自己觉得重要又可能忘记的东西 用模块模式产生安全的对象: var serial_maker = function () { var preifx = ''; var seq = 0; return ...
- Jmeter HTTP请求后响应数据显示乱码解决方法
Jmeter请求后结果树里无论是text还是html响应数据显示乱码,这是因为jmeter 编码格式配置文件默认不开启导致的,解决方法如下: 1)进入jmeter-***\bin目录下,找到jmete ...
- Linux链接脚本学习--lds
一.概论 ld: GNU的链接器. 用来把一定量的目标文件跟档案文件链接在一起,并重新定位它们的数据,链接符号引用. 一般编译一个程序时,最后一步就是运行ld进行链接 每一个链接都被一个链接脚本所控制 ...
- 【LeetCode】13. 罗马数字转整数
题目 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M. 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做 II ,即为 ...
- iOS之Settings.Bundle的应用
Settings.Bundle Settings.Bundle支持六种配置项分别是:Title,MultiValue,Group,Slider,ToggleSwitch,TextField . Tit ...
- Linux Shell常用shell命令
Linux Shell常用shell命令 一.文件.目录操作命令 1.ls命令 功能:显示文件和目录的信息 ls 以默认方式显示当前目录文件列表 ls -a 显示所有文件包括隐藏文件 ls -l 显示 ...
- [每天解决一问题系列 - 0010] ADB Not Responding - Android Studio
问题描述: 最近安装了Android Studio v1.0,运行的时候老是这个错误 解决方案: 网上有人说是已经有adb的进程在运行,可是打开任务管理器,找不到对应的adb 进程. 无奈之下,想到a ...