c++ References vs. Pointers

C++中指针(pointer)和引用(reference)的区别和联系 估计很多人在编写C++程序都或多或少的会用到pointer 和 reference这两种东西,但是他们两者到底有什么样的区别和联系呢,相信大多数人是不太了解的,今天我就两者的区别和联系从实际程序的角度来加以区别。C/C++中的指针其实就是一个变量,和其他类型的变量是一个样子的,它是一个占用四字节的变量(32位机上),它与其他变量的不同之处就在于它的变量值是一个内存地址,指向内存的另外一个地方。re 阅读详情

 Reference

1. If you are familiar with Java/C#, treat reference as Java/C# reference. unlike in java/C#, which always do referene copy, e.g, obj1 = obj2. In c++, all the copy is value copy of object unless use reference explictly.

2. If you are not familiar with Java/C#, treat reference as Alias. A sam object can have several names.

 

So a simple rule: when use reference ?

You want avoid copy or you want manipulate the object instead of a copy.

Pointer

when use pointer ?

array

 

when not use ?

 

>如果“指針”這名詞是你從書上看來的話,這本書建議你不要再看了,
>會誤導你的…
指針是大陸用詞,除了在綠色執政時會誤你官途外,其它狀況用之無礙


 

 

http://www.embedded.com/story/OEG20010311S0024

 

Knowing how references really differ from pointers should help you decide when to use references and when to stick with pointers.

 

In C++, references provide many of the same capabilities as pointers. Although most C++ programmers seem to develop some intuition about when to use references instead of pointers, and vice versa, they still encounter situations where the choice isn't so clear. If you'd like to develop a reasonably consistent philosophy about using references, it really helps to know exactly how references differ from pointers. Those differences are my subject this month.

 

More than skin deep

 

A reference, like a pointer, is an object that you can use to refer indirectly to another object. A reference declaration has essentially the same syntactic structure as a pointer declaration. The difference is that while a pointer declaration uses the * operator, a reference declaration uses the & operator. For example, given:

 

int i = 3;

 

then:

 

int *pi = &i;

 

declares pi as an object of type "pointer to int" whose initial value is the address of object i. On the other hand:

 

int &ri = i;

 

declares ri as an object of type "reference to int" referring to i. The difference between pointer and reference declarations is noteworthy, but it's not the basis for deciding to use one over the other. The real basis for the choice is the difference in appearance between references and pointers when you use them in expressions.

 

The big difference between pointers and references is that you must use an explicit operator-the * operator-to dereference a pointer, but you don't use an operator to dereference a reference. For example, once the previous declarations are in place, the indirection expression *pi derefences pi to refer to i. In contrast, the expression ri-without any operators at all-dereferences ri to refer to i. Thus, an assignment such as: *p = 4;

 

changes the value of i to 4, as does the assignment:

 

ri = 4;

 

This difference in appearance is significant when you're choosing between pointers and references for function parameter types and return types. This is especially true in functions that declare overloaded operators.

 

In my first column on references, I illustrated this point with the example of defining a ++ operator for an enumeration type.1 In C++, the built-in ++ operator does not apply to enumerations. For example, given just:

 

 

enum day
{
Sunday, Monday, ...
};

 

day x;

 

the expression ++x does not compile. If you want it to, you must define a function named operator++ which accepts a day as an argument.

 

Invoking ++x should change the value in x. Therefore, declaring operator++ with a parameter of type day, as in:

 

day operator++(day d);

 

won't have the desired effect. This function passes its argument by value, which means the function sees a copy of the argument, not the argument itself. For the function to alter the value of its operand, it must pass that operand either by a pointer or by a reference.

 

Passing the argument by a pointer, as in:

 

day *operator++(day *d);

 

would let the function alter the value of the day by storing the incremented value into *d. However, you would then invoke the operator using an expression such as ++&x, which doesn't look right.

 

The proper way to define operator++ is with a reference as the parameter type, as in:

 

 

day &operator++(day &d)
{
d = (day)(d + 1);
return d;
}

 

Using this function, expressions such as ++x have the proper appearance as well as the proper behavior.

 

Passing by reference is not just the better way to write operator++, it's the only way. C++ doesn't really give you a choice here. A declaration such as:

 

day *operator++(day *d);

 

does not compile. Every overloaded operator function must either be a member of a class, or have a parameter of type T, T &, or T const &, where T is a class or enumeration type. In other words, every overloaded operator must accept an argument of a class or enumeration type. A pointer, even to an object of class or enumeration type, doesn't count. C++ does not let you overload operators that redefine the meaning of operators for built-in types, including pointer types. Thus, you cannot declare:

 

int operator++(int i); // error

 

which attempts to redefine the meaning of ++ for int, nor can you declare:

 

int *operator++(int *i); // error

 

which attempts to redefine ++ for int *.

 

References vs. const pointers

 

In my last column, I explained that C++ doesn't let you declare a "const reference" because a reference is inherently const.2 In other words, once you bind a reference to refer to an object, you cannot rebind it to refer to a different object. There's no notation for rebinding a reference after you've declared the reference. For example:

 

int &ri = i;

 

binds ri to refer to i. Then an assignment such as:

 

ri = j;

 

doesn't bind ri to j. It assigns the value in j to the object referenced by ri, namely, i.

 

In short, whereas a pointer can point to many different objects during its lifetime, a reference can refer to only one object during its lifetime. Some people claim that's a significant difference between references and pointers. I'm not sold on the idea. Maybe this is a difference between references and pointers, but it's not a difference between references and const pointers. Again, once you bind a reference to an object, you can't change it to refer to something else. Since you can't change the reference after you bind it, you must bind the reference at the beginning of its lifetime. Otherwise, the reference will never be bound to anything and will be useless, if not downright dangerous.

 

All of the statements in the previous paragraph apply to const pointers just as much as they do to references. (I'm talking about "const pointers" here, not about "pointers to const.") For example, a reference declaration at block scope must have an initializer, as in:

 

 

void f()
{
int &r = i;
...
}

 

Omitting the initializer produces a compile-time error:

 

 

void f()
{
int &r; // error
...
}

 

A const pointer declaration at block scope must also have an initializer, as in:

 

 

void f()
{
int *const p = &i;
...
}

 

Omitting the initializer is just as much an error:

 

 

void f()
{
int *const p; // error
...
}

 

In my opinion, the fact that you can't rebind a reference is no more a difference between references and pointers than that which exists between const pointers and non-const pointers.

 

Null references

 

Appearances aside, const pointers differ from references in one subtle but significant way. A valid reference must refer to an object; a pointer need not. A pointer, even a const pointer, can have a null value. A null pointer doesn't point to anything.

 

This difference suggests that you should use a reference as a parameter type when you want to insist that the parameter refer to an object. For example, let's revisit the swap function, which accepts two int arguments and swaps the value of its first argument with the value of its second argument. For example:

 

 

int i, j;
...
swap(i, j);

 

leaves the value that was in i in j, and the value that was in j in i. You could write this function as:

 

 

void swap(int *v1, int *v2)
{
int temp = *v1;
*v1 = *v2;
*v2 = temp;
}

 

so that a call looks like: swap(&i, &j);

 

This interface suggests that either or both arguments might be a null pointer. The suggestion is misleading. For example, the consequences of calling: swap(&i, NULL);

 

are likely to be unpleasant. Defining the function with reference parameters, as in:

 

 

void swap(int &v1, int &v2)
{
int temp = v1;
v1 = v2;
v2 = temp;
}

 

clearly suggests that a call to swap should provide two objects whose values will be swapped. As an added bonus, calls to this function look nicer without the &s cluttering things up:

 

swap(i, j);

 

Greater safety?

 

Some people take the fact that a reference can't be null to mean that references are somehow safer than pointers. They may be a little safer, but I don't think they're a lot safer. Although a valid reference can't be null, an invalid one can be null. In fact, there's a ton of ways programs can produce invalid references, not just null references. For example, you can define a reference so that it refers to the object addressed by a pointer, as in:

 

 

int *p;
...
int &r = *p;

 

If the pointer happens to be null at the time of the reference definition, the reference is a null reference. Technically, the error is not in binding the reference, but in dereferencing the null pointer. Dereferencing a null pointer produces undefined behavior, which means lots of things could happen, and most of them aren't good. It's likely that, when the program binds reference r to *p (the object that p points to), it won't actually dereference p. Rather, it will just copy the value of p to the pointer that implements r. The program will keep running only to have the error manifest itself more overtly sometime later during program execution. Oh joy.

 

The following function shows another way to produce an invalid reference:

 

 

int &f()
{
int i;
...
return i;
}

 

This function returns a reference to local variable i. However, the storage for i vanishes as the function returns. Thus, the function returns a reference to deallocated storage. The behavior is the same as returning a pointer to a local variable. Some compilers do detect this particular error at compile time. However, you can disguise the sin so it will go undetected.

 

I like references. There are good reasons to use them instead of pointers. But, if you expect that using references will make your program significantly more robust, you're likely to be disappointed.

 

My bad

 

In my last column, I explained that although you can't define a "const reference" directly you can do it indirectly through a typedef. I gave this example:

 

 

typedef int &ref_to_int;
...
int_ref const r = i;

 

That second line should have been:

 

ref_to_int const r = i;

Dan Saks is a high school track coach and the president of Saks & Associates, a C/C++ training and consulting company. He is also a consulting editor for the C/C++ Users Journal. He served for many years as secretary of the C++ standards committee. You can write to him at dsaks@wittenberg.edu.

 

UIUC CS225数据结构课程:C++实现与双语字幕学习指南 数据结构是计算机科学的核心基础,它研究数据的组织、存储和操作方式,直接影响算法的效率。其原理在于通过抽象数据类型(ADT)定义逻辑结构,并利用数组、链表等物理结构实现,以优化数据的查找、插入和删除操作。掌握数据结构的技术价值在于能够为复杂问题设计高效的解决方案,提升软件性能,是构建大型系统和通过技术面试的基石。应用场景广泛,涵盖数据库索引、编译器设计、网络路由和人工智能等领域。本文聚焦于UIUC CS225这门经典课程,它通过体系化的C++教学和高质量的中英双语字幕,为学习者提供了从指针、链表到图论算法的完 阅读详情

相关推荐

C++无锁编程性能陷阱剖析与系统化优化实践

并发编程是构建高性能系统的核心技术,其核心挑战在于如何安全高效地协调多线程对共享资源的访问。传统基于锁的同步机制虽然直观,但在高竞争场景下可能引发线程阻塞、上下文切换等开销,成为性能瓶颈。无锁编程通过原子操作和内存屏障,避免了显式锁带来的阻塞,理论上能实现更高的吞吐量和更低的延迟。然而,这项技术并非银弹,它将同步的代价从操作系统调度转移到了CPU流水线、缓存一致性和算法复杂性层面。在实践中,开发者常面临伪共享导致的缓存行乒乓、忙等待造成的CPU资源浪费、ABA问题带来的正确性与内存管理挑战,以及对C++内存

weixin_30729609的博客 472

仔细认识c++ 中pointers和references。

指针和引用看起来很不一样(pointers使用"* "和"->"操作符, references使用 "."),但用起来总觉得很相似。下面就仔细抠一下它俩之间的相同和不同之处,以及各自的使用场合。 首先必须认知一点,引用没有 null references。 一个引用必须代表一个对象。所以如果你使用一个变量指向(代表)另一个对象。但是它也有可能不指向任何对象,这时候要用指针。如果你的设计并不允许这个变

你的目光看海的博客 811

【信息科学与工程学】计算机科学与自动化——第三百零五篇 计算机系统中的各类运算操作01

编号类型领域运算操作运算类型算法算法的详细设计及数学分析参数列表及参数的数值设计应用场景 (100+条)集合运算​1集合运算关系代数并集 (Union)集合运算归并排序去重合并两个集合,去除重复元素。时间复杂度 O(n+m),n,m为两集合大小。输入:集合A, B。输出:A∪B。数据集成、多表结果合并、去重后的全量数据提取。2集合运算关系代数交集 (Intersection)集合运算哈希交集找出同时属于两个集合的元素。平均时间复杂度 O(min(n,m)),最坏 O(n*m)。输入:集合A, B。输出:A∩

weixin_49199313的博客 1390

C++之引用

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34393428的博客 102

高分系列卫星轨道、传感器参数等信息

遥感卫星数据简介-高分系列

中遥科 3310

CPU进程调度算法【FCFS、SJF、优先级、RR、多级队列、多级反馈队列调度】

目录 一、先到先服务调度: 二、最短作业优先调度: 三、优先级调度: 四、轮转调度: 五、多级队列调度: 六、多级反馈队列调度: CPU调度算法处理的问题是:从就绪队列中选择进程以便为其分配CPU。 一、先到先服务调度: First Come,First Served(FCFS) 定义:先请求CPU的进程首先分配到CPU。FCFS策略可以通过FIFO队列轻松实现。 护航效果:其他所有进程会等待一个大进程释放CPU 非抢占式:一旦CPU分配给了一个进程,该进程就会使用CPU知道释.

马小超 3922

详解c++ 引用(reference)与 指针(pointer)的区别与联系

引用(reference) 与指针(pointer)之间有什么区别和联系呢?我相信,对于很多初学c++的程序猿来说,不是一件简单的事.那么在c++中,引用与指针到底有什么联系和区别呢?要弄清楚这个问题,我们必须明白 : 1.什么是引用?什么是指针? 2.为什么要用引用?为什么要用指针? 3.引用和指针有什么优缺点? 4.怎样使用引用和指针? 5.引用与指针有什么联系和区别? 下面容小生

tianxiaolu1175的专栏 2万+

基于mediapipe的动作捕捉和unity的人物模型驱动

用到的人体关键点检测的算法是Google开发的基于深度学习的实时多媒体套件,汇集了人体、手部、人脸关键点追踪、物体检测、物体识别等多个流行的视觉任务的成果。整套 Mediapipe正如其名字,专门为便携设备上的多媒体应用设计,模型非常小,在笔记本手机上也能实时跑,跨平台、跨语言。mediapipe实时性是没什么问题。但是是以牺牲了质量为代价的,这种关键点检测一般是用来做动作识别,类似于运动app跳绳计数、判定瑜伽动作标不标准这种。用单目视觉来做人物模型的驱动,总差点意思。

qq_58484580的博客 5728

pointer和reference的比较

转 引用(reference)和指针(pointer)是学C++过程中最令人头疼的问题,常常不知道什么时候用哪个合适,又常常弄混。找到Dan Saks的这篇文章,讲的很清楚,强烈推荐。 ——————————————————————————— 以下译自Dan Saks的文章 References vs. Pointers 英文原文 ————————————————————

luqichao的专栏 1081

Pinocchio 结合 CasADi 进行 IK 逆运动学及 Mujoco 仿真

摘要:本视频演示了如何利用Pinocchio和CasADi实现机械臂逆运动学(IK)求解,并在Mujoco中进行仿真。通过构建优化问题(最小化位姿误差),结合IPOPT求解器对机械臂关节角度进行优化。代码支持导入URDF/MJCF模型,并以so100机械臂为例,实现了末端执行器位置跟踪的仿真测试。关键步骤包括:建立平移/旋转误差函数、设置约束条件、调用CasADi求解,最终在Mujoco中实时更新关节状态完成运动控制。

darcsdn 1004

FineReport V11.0安装避坑指南:从下载到激活的完整流程(附百度网盘链接)

本文提供FineReport V11.0从下载、安装到激活的完整避坑指南。详细解析了部署前的环境准备、安装过程中的JVM内存等核心配置、激活流程以及安装后的优化与常见问题排查,旨在帮助用户一次部署成功,确保企业级报表平台的稳定运行。

echo99的专栏 1198

c++ Pointers vs References

1. Pointers References int i; int i; int *pi = &i; int &ri = i; In both cases the situation is as follows: Both pi and ri contain addresses that point to the location of i, but the difference l

沉淀 478

芒果YOLO11改进59:分类损失函数Loss篇FocalLoss:即插即用|最新改进FocalLoss损失函数,提高处理不平衡数据分类场景下的任务性能,提升YOLO11检测精度

即插即用|最新改进FocalLoss损失函数,提高处理不平衡数据分类场景下的任务性能,提升YOLO11检测精度

包括YOLOv5、YOLOv7、YOLOv8等模型改进 555

【C++ Basics】 区别pointers和references

reference是一种特殊的pointer。

Zoey的博客 228

【WRFDA教程第一期】运行观测预处理程序(OBSPROC)

运行观测预处理程序(OBSPROC)

WW、forever的博客 1900

YOLO11改进-模块-引入多尺度差异融合模块MDFM

MDFM主要用于融合双时相图像特征并生成带有丰富上下文信息的差异特征,其过程包含以下步骤:1. 特征提取与差异特征生成首先从双时相图像中提取特征f1和f2,然后将f1和f2进行像素级别的相减,再对相减结果取绝对值,最后通过一个3x3的卷积操作得到Di。2. 多尺度特征融合(MSFF)接着利用多尺度特征学习机制来增强特征融合效果。该机制通过不同核大小的卷积构建多尺度融合过程,具体是通过一个名为 MSFF 单元来实现的。

qq_64693987的博客 4381

golang 中Pointers Vs References

原文:https://spf13.com/post/go-pointers-vs-references/ Pointers Vs References Some languages including C, C++ support pointers. Other languages including C++, Java, Python, Ruby, Perl and PHP all s...

weixin_30701575的博客 193

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Effective C++ 笔记(二)

E27 尽量少做转型动作转型动作会产生副本。2)真正调用了A类的fun函数,而1)却调用了转型产生的临时对象的函数,如果涉及到修改对象的数据,真正被修改数据的是临时对象,而不是this。1) static_castA>(*this).fun();     2) A::fun();尽量避免dynamic_cast操作,尝试寻找其他替代方案。如果转型是必要的,那就将其封装在一个函数

苹果君的工作室 3029

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

【The Cherno C++】00. 目录与学习规划

Part 3. C++函数与算法结构。Part 2. 组成成分与预设置。Part 1. 基本原理。

hotpants的博客 499

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Reference and pointer C++

References vs PointersBoth references and pointers can be used to change local variables of one function inside another function. Both of them can also be used to save copying of big objects when pass...

weixin_30477293的博客 259

【一文读懂】《More Effective C++》35个改善程序与设计的有效方法

《More Effective C++》是 Meyers 继《Effective C++》后的进阶作品,35 个条款专注指针/多态、运算符重载、异常、效率、实现技巧,涉及智能指针、代理类、引用计数、表达式模板等高级技术。

码工许师傅 374

The differences between pointer and reference in C++

I'm learning C++ from LearnCpp, you should read it before this article. There is an example just like this: [c language="++"] class Calc { private: int m_nValue; public: Calc() { m_nValue = 0; }...

weixin_30535043的博客 175

CPU 缓存 | 原理、映射、一致性

……

u013669912的博客 415

深挖C++:类和对象(中)

(先进后出)

xys_678的博客 258

跟我学c++中级篇—类型定义的方式

本文系统阐述了编程中类型定义的重要性及c++中的实现方式。重点对比了宏定义、typedef与modern using三种机制,指出using在可读性、灵活性和模板支持上的优势,推荐优先使用。同时提醒开发者注意别名滥用、类型歧义、错误信息冗长等问题,强调统一规范与合理设计。最终结论:在现代c++开发中,应以using为主,兼顾简洁性与可维护性,避免陷入命名混乱与编译困境。

fpcc的专栏 397

【C/C++ 第一次跨越(下):移动语义与 noexcept——不改变行为的性能修复】

本文详解C++11移动语义在迁移至现代C++时的性能优化策略,强调“不改变行为”的前提下通过合理使用移动语义消除深拷贝开销。重点解析移动操作生成规则:析构函数、拷贝函数或const/引用成员会抑制移动构造;noexcept影响std::vector是否选择移动而非回退拷贝。提出“Rule of Zero”原则——用RAII封装资源,避免手动实现特殊成员函数,确保移动语义被正确调用,实现零开销移动与内存安全。

一起学习进步! 245
上一篇: Programmer Competency Matrix
下一篇: pervasive myths older software developers (五个广泛流传的对大龄程序员的误解)
FireCoder
博客等级 码龄17年 65粉丝 100原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值