When do we pass arguments by reference or pointer?
在C++中,基于以下如下我们通过以引用reference的形式传递变量。
(1)To modify local variables of the caller function
A reference(or pointer) allows called function to modify a local variable of the caller function.
For example, consider te following example program where fun() is able to modify local variable x of main().
1 #include<iostream>
2 using namespace std;
3
4 void fun(int &x)
5 {
6 x = 20;
7 }
8
9 int main()
10 {
11 int x = 10;
12 fun(x);
13 cout<<"New value of x is "<<x;
14 return 0;
15 }
Output:
New value of x is 20
(2)For passing large sized arguments
If an argument is large, passing by reference (or pointer) is more efficient because only an address is really passed, not the entire object.
For example, let us consider the following Employee class and a function printEmpDetails() that prints Employee details.
1 class Employee
2 {
3 private:
4 string name;
5 string desig;
6
7 // More attributes and operations
8 };
9
10 void printEmpDetails(Employee emp)
11 {
12 cout<<emp.getName();
13 cout<<emp.getDesig();
14
15 // Print more attributes
16 }
The problem with above code is: every time printEmpDetails() is called, a new Employee abject is constructed that involves creating a copy of all data members. So a better implementation would be to pass Employee as a reference.
1 void printEmpDetails(const Employee &emp)
2 {
3 cout<<emp.getName();
4 cout<<emp.getDesig();
5
6 // Print more attributes
7 }
This point is valid only for struct and class variables as we don’t get any efficiency advantage for basic types like int, char.. etc.
(3)To avoid object slicing
If we pass an object of subclass to a function that expects an object of superclass then the passed object is sliced if it is pass by value.
For example, consider the following program, it prints “This is Pet Class”.
1 #include <iostream>
2 #include<string>
3
4 using namespace std;
5
6 class Pet
7 {
8 public:
9 virtual string getDescription() const
10 {
11 return "This is Pet class";
12 }
13 };
14
15 class Dog : public Pet
16 {
17 public:
18 virtual string getDescription() const
19 {
20 return "This is Dog class";
21 }
22 };
23
24 void describe(Pet p)
25 {
26 // Slices the derived class object
27 cout<<p.getDescription()<<endl;
28 }
29
30 int main()
31 {
32 Dog d;
33 describe(d);
34 return 0;
35 }
Output:
This is Pet class.
If we use pass by reference in the above program then it correctly prints “This is Dog Class”.
See the following modified program.
1 #include <iostream>
2 #include<string>
3
4 using namespace std;
5
6 class Pet
7 {
8 public:
9 virtual string getDescription() const
10 {
11 return "This is Pet class";
12 }
13 };
14
15 class Dog : public Pet
16 {
17 public:
18 virtual string getDescription() const
19 {
20 return "This is Dog class";
21 }
22 };
23
24 void describe(const Pet &p)
25 {
26 // Doesn't slice the derived class object.
27 cout<<p.getDescription()<<endl;
28 }
29
30 int main()
31 {
32 Dog d;
33 describe(d);
34 return 0;
35 }
Output:
This is Dog class
This point is also not valid for basic data types like int, char, .. etc.
(4)To achieve Run Time Polymorphism in a function
We can make a function polymorphic by passing objects as reference (or pointer) to it.
For example, in the following program, print() receives a reference to the base class object. print() calls the base class function show() if base class object is passed, and derived class function show() if derived class object is passed.
1 #include<iostream>
2 using namespace std;
3
4 class base
5 {
6 public:
7 virtual void show()
8 { // Note the virtual keyword here
9 cout<<"In base \n";
10 }
11 };
12
13
14 class derived: public base
15 {
16 public:
17 void show()
18 {
19 cout<<"In derived \n";
20 }
21 };
22
23 // Since we pass b as reference, we achieve run time polymorphism here.
24 void print(base &b)
25 {
26 b.show();
27 }
28
29 int main(void)
30 {
31 base b;
32 derived d;
33 print(b);
34 print(d);
35 return 0;
36 }
Output:
In base
In derived
As a side note, it is a recommended practice to make reference arguments const if they are being passed by reference only due to reason no. 2 or 3 mentioned above. This is recommended to avoid unexpected modifications to the objects.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-25 21:56:14
When do we pass arguments by reference or pointer?的更多相关文章
- [NPM] Pass arguments to npm scripts
Often times you’ll have variations that you’ll want to make to your npm scripts and repeating yourse ...
- C++中Reference与Pointer的不同
Reference与Pointer中直接存储的都是变量的地址, 它们唯一的不同是前者的存储的地址值是只读的, 而后者可以修改. 也就是说Reference不支持以下操作: *a = b 其他语言, 如 ...
- variadic templates & pass by const reference & member operator [] in const map & gcc sucks
/// bugs code with comments #include <iostream> #include <memory> #include <unordered ...
- Drupal 7.23:函数module_invoke_all()注释
/** * Invokes a hook in all enabled modules that implement it. * * All arguments are passed by value ...
- 北京地铁换乘算法(二维坐标系,图的深度搜索)开源下载Android源码、性能最优解
距离2012年11月2日下午2:05:31 已经过去158751270这么多秒了,不小心暴露了我的当前时间. java代码贴出来. private static long gettimelong() ...
- 这个拖后腿的“in”
问题之源 C# 7.2推出了全新的参数修饰符in,据说是能提升一定的性能,官方MSDN文档描述是: Add the in modifier to pass an argument by referen ...
- 5.Primitive, Reference, and Value Types
1.Programming Language Primitive Types primitive types:Any data types the compiler directly supports ...
- Python中的passed by assignment与.NET中的passing by reference、passing by value
Python文档中有一段话: Remember that arguments are passed by assignment in Python. Since assignment just cre ...
- CRM 2016 自动保存 Save event arguments
Save event arguments (client-side reference) Applies To: Dynamics CRM 2016, Dynamics CRM Online In ...
随机推荐
- CTF-Tools 一款CTF古典密码加解密工具
CTF-Tools 一款CTF古典密码加解密工具 工具截图 工具简介 一款CTF编码.解码.加密.解密工具. 支持的编码解码: URL-UTF-8 URL-GB2312 Unicode Escape( ...
- Java8新特性之Optional,如何优雅地处理空指针
是什么 从 Java 8 引入的一个很有趣的特性是 Optional 类.Optional 类主要解决的问题是臭名昭著的空指针异常(NullPointerException)-- 每个 Java ...
- SQL 添加列,删除列,修改列的类型
alter table 表名 add 列名 数据类型 如:alter table student add nickname char(20) alter table tableName(表名) add ...
- flume的配置详解
Flume:===================== Flume是一种分布式的.可靠的.可用的服务,可以有效地收集.聚合和移动大量的日志数据. 它有一个基于流数据的简单而灵活的体系结构. 它具有健壮 ...
- Centos8 Docker部署ElasticSearch集群
ELK部署 部署ElasticSearch集群 1.拉取镜像及批量生成配置文件 # 拉取镜像 [root@VM-24-9-centos ~]# docker pull elasticsearch:7. ...
- dart系列之:创建Library package
目录 简介 Library package的结构 导入library 条件导入和导出library 添加其他有效的文件 library的文档 发布到pub.dev 总结 简介 在dart系统中,有pu ...
- [nowcoder5669H]Harder Gcd Problem
题目相当于问1-n中最多能选出多少对不互素无交集的二元组,并要求方案 构造:将所有数放入其最小质因子对应的集合,若素数p所对应的集合元素个数为奇数且$p\ne 2$且$2p\le n$,那么就将$2p ...
- [bzoj4945]游戏
暴力枚举$2^{d}$表示这d个点中一定不选A或一定不选B(那么就包含了所有情况),然后就对原图跑2-sat即可注意一个细节,如果某一条限制中初始点不合法,就不用管了:如果最终点不合法,那么相当于初始 ...
- 【.NET 6】使用.NET 6开发minimal api以及依赖注入的实现、VS2022热重载和自动反编译功能的演示
前言: .net 6 LTS版本发布已经有若干天了.此处做一个关于使用.net 6 开发精简版webapi(minimal api)的入门教程,以及VS2022 上面的两个强大的新技能(热重载.代码自 ...
- .NET 5的System.Text.Json的JsonDocument类讲解
本文内容来自我写的开源电子书<WoW C#>,现在正在编写中,可以去WOW-Csharp/学习路径总结.md at master · sogeisetsu/WOW-Csharp (gith ...