深入分析C++引用

Normal
0

7.8 磅
0
2

false
false
false

EN-US
ZH-CN
X-NONE

MicrosoftInternetExplorer4

关于引用和指针的差别的文章非常多非常多,可是总是找不到他们的根本差别,偶然在codeproject上看到这篇文章,认为讲的挺好的,

所以翻译了下,希望对大家有帮助。

原文地址: http://www.codeproject.com/KB/cpp/References_in_c__.aspx

引言

我选择写
C++
中的引用是由于我感觉大多数人误解了引用。而我之所以有这个感受是由于我主持过非常多
C++
的面试,而且我非常少从面试者中得到关于
C++
引用的正确答案。

那么
c++
中引用究竟意味这什么呢?通常一个引用让人想到是一个引用的变量的别名,而我讨厌将
c++
中引用定义为变量的别名。这篇文章中,我将尽量解释清楚,
c++
中根本就没有什么叫做别名的东东。

背景


c/c++
中,訪问一个变量仅仅能通过两种方式被訪问,传递,或者查询。这两种方式是:

1.
通过值
訪问
/
传递变量

2.
通过地址
訪问
/
传递变量

这样的方法就是指针

除此之外没有第三种訪问和传递变量值的方法。引用变量也就是个指针变量,它也拥有内存空间。最关键的是引用是一种会被编译器自己主动解引用的指针。非常难相信么?让我们来看看吧。。。

以下是一段使用引用的简单
c++
代码

#include <iostream.h>
int main()
{
int i = 10; // A simple integer variable
int &j = i; // A Reference to the variable i
j++; // Incrementing j will increment both i and j.
// check by printing values of i and j
cout<< i << j <<endl; // should print 11 11
// Now try to print the address of both variables i and j
cout<< &i << &j <<endl;
// surprisingly both print the same address and make us feel that they are
// alias to the same memory location.
// In example below we will see what is the reality
return 0;
}

引用事实上就是
c++
中的常量指针。表达式
 
int &i = j;
将会被编译器转化成
int *const i = &j;
而引用之所以要初始化是由于
const
类型变量必须初始化,这个指针也必须有所指。以下我们再次聚焦到上面这段代码,并使用编译器的那套语法将引用替换掉。

#include <iostream.h>
int main()
{
int i = 10; // A simple integer variable
int *const j = &i; // A Reference to the variable i
(*j)++; // Incrementing j. Since reference variables are
// automatically dereferenced by compiler
// check by printing values of i and j
cout<< i << *j <<endl; // should print 11 11
// A * is appended before j because it used to be reference variable
// and it should get automatically dereferenced.
return 0;
}

读者一定非常奇怪为什么我上面这段代码会跳过打印地址这步。这里须要一些解释。由于引用变量时会被编译器自己主动解引用的,那么一个诸如
 
cout << &j
<< endl;
的语句,编译器就会将其转化成语句
 
cout << &*j << endl;

如今
&*
会相互抵消,这句话变的毫无意义,而
cout
打印的
j
值就是
i
的地址,由于其定义语句为
int *const
j = &i;

所以语句
cout << &i << &j << endl;
变成了
cout << &i << &*j << endl;
这两种情况都是打印输出
i
的地址。这就是当我们打印普通变量和引用变量的时候会输出同样地址的原因。

以下给出一段复杂一些的代码,来看看引用在级联
(cascading)
中是怎样运作的。

#include <iostream.h>
int main()
{
int i = 10; // A Simple Integer variable
int &j = i; // A Reference to the variable
// Now we can also create a reference to reference variable.
int &k = j; // A reference to a reference variable
// Similarly we can also create another reference to the reference variable k
int &l = k; // A reference to a reference to a reference variable.
// Now if we increment any one of them the effect will be visible on all the
// variables.
// First print original values
// The print should be 10,10,10,10
cout<< i << "," << j << "," << k << "," << l <<endl;
// increment variable j
j++;
// The print should be 11,11,11,11
cout<< i << "," << j << "," << k << "," << l <<endl;
// increment variable k
k++;
// The print should be 12,12,12,12
cout<< i << "," << j << "," << k << "," << l <<endl;
// increment variable l
l++;
// The print should be 13,13,13,13
cout<< i << "," << j << "," << k << "," << l <<endl;
return 0;
}

以下这段代码是将上面代码中的引用替换之后代码,也就是说明我们不依赖编译器的自己主动替换功能,手动进行替换也能达到同样的目标。

#include <iostream.h>
int main()
{
int i = 10; // A Simple Integer variable
int *const j = &i; // A Reference to the variable
// The variable j will hold the address of i
// Now we can also create a reference to reference variable.
int *const k = &*j; // A reference to a reference variable
// The variable k will also hold the address of i because j
// is a reference variable and
// it gets auto dereferenced. After & and * cancels each other
// k will hold the value of
// j which it nothing but address of i
// Similarly we can also create another reference to the reference variable k
int *const l = &*k; // A reference to a reference to a reference variable.
// The variable l will also hold address of i because k holds address of i after
// & and * cancels each other.
// so we have seen that all the reference variable will actually holds the same
// variable address.
// Now if we increment any one of them the effect will be visible on all the
// variables.
// First print original values. The reference variables will have * prefixed because
// these variables gets automatically dereferenced.
// The print should be 10,10,10,10
cout<< i << "," << *j << "," << *k << "," << *l <<endl;
// increment variable j
(*j)++;
// The print should be 11,11,11,11
cout<< i << "," << *j << "," << *k << "," << *l <<endl;
// increment variable k
(*k)++;
// The print should be 12,12,12,12
cout<< i << "," << *j << "," << *k << "," << *l <<endl;
// increment variable l
(*l)++;
// The print should be 13,13,13,13
cout << i << "," << *j << "," << *k << "," << *l <<endl;
return 0;
}

我们通过以下代码能够证明
c++
的引用不是神马别名,它也会占用内存空间的。

#include <iostream.h>
class Test
{
int &i; // int *const i;
int &j; // int *const j;
int &k; // int *const k;
};
int main()
{
// This will print 12 i.e. size of 3 pointers
cout<< "size of class Test = " << sizeof(class Test) <<endl;
return 0;
}

结论

我希望这篇文章能把
c++
引用的全部东东都解释清楚,然而我要指出的是
c++
标准并没有解释编译器怎样实现引用的行为。所以实现取决于编译器,而大多数情况下就是将事实上现为一个
const
指针。

引用支持
c++
虚函数机制的代码

#include <iostream.h>
class A
{
public:
virtual void print() { cout<<"A.."<<endl; }
};
class B : public A
{
public:
virtual void print() { cout<<"B.."<<endl; }
};

class C : public B
{
public:
virtual void print() { cout<<"C.."<<endl; }
};
int main()
{
C c1;
A &a1 = c1;
a1.print(); // prints C
A a2 = c1;
a2.print(); // prints A
return 0;
}

上述代码使用引用支持虚函数机制。假设引用不过一个别名,那怎样实现虚函数机制,而虚函数机制所须要的动态信息只能通过指针才干实现,所以更加说明引用事实上就是一个
const
指针。

时间: 2024-08-08 09:41:44

深入分析C++引用的相关文章

[引用区别] c++中引用与java中引用区别

综述: 在Java中,类实例声明和构造是分开."T a;"是声明,而"a=new T();"才是构造.引用声明和C++相同.但是Java的机制与C++不同,Java中的引用也叫句柄,或者说句柄才是其真实名称.类声明的都是一个句柄,调用构造函数才会使得句柄指向类实例.因此Java中没有类似于C++中的复制函数,因为Java的复制都是直接复制句柄内容.例如"T b=a;"只不过是将a的句柄复制(赋值)给了b,从而b也指向a指向的类实例.可以看出Jav

JAVA随笔篇二(深入分析JAVA简单类型、String和对象的值传递和引用传递)

关于JAVA的值传递和引用传递,翻看了很多资料和博客,感觉大多数讲的很乱,都是自己明白了之后就不讲了的样子,终于算是比较理解这几个概念了,下面做一个总结. 1.简单类型的参数传递 Java方法的参数是简单类型的时候,是按值传递的 (pass by value).下面举一个经典的swap函数: 无法交换值的方法: package TestTransferPack; public class TestTransfer { public static void main(String[] args)

[转]数组引用:C++ 数组做参数 深入分析

"数组引用"以避免"数组降阶"(本文曾贴于VCKBASE\C++论坛) 受[hpho]的一段模板函数的启发,特写此文,如有雷同,实在遗憾. 数组降阶是个讨厌的事,这在C语言中是个无法解决的问题,先看一段代码,了解什么是"数组降阶" #include <IOSTREAM> using namespace std; void Test( char array[20] ) {     cout << sizeof(array)

深入分析Volatile的实现原理

引言 在多线程并发编程中synchronized和Volatile都扮演着重要的角色,Volatile是轻量级的synchronized,它在多处理器开发中保证了共享变量的"可见性".可见性的意思是当一个线程修改一个共享变量时,另外一个线程能读到这个修改的值.它在某些情况下比synchronized的开销更小,本文将深入分析在硬件层面上Inter处理器是如何实现Volatile的,通过深入分析能帮助我们正确的使用Volatile变量. 术语定义 术语 英文单词 描述 共享变量   在多

深入分析同步工具类之CountDownLatch

概览: CountDownLatch又称闭锁,其作用是让一个或者多个线程挂起,直到其他的线程执行完后恢复挂起的线程,使其继续执行.内部维护着一个静态内部类Sync,该类继承AbstractQueuedSynchronizer(这个类之前分析过了,参见    深入分析同步工具类之AbstractQueuedSynchronizer),Sync实例维护着state属性,调用await()方法,使当前线程挂起,当一个线程执行完后,调用countDown()方法,state-1,直到state变为0,被

Google GFS文件系统深入分析

Google GFS文件系统深入分析 现在云计算渐成潮流,对大规模数据应用.可伸缩.高容错的分布式文件系统的需求日渐增长.Google根据自身的经验打造的这套针对大量廉价客户机的Google GFS文件系统已经广泛的在Google内部进行部署,对于有类似需求的企业而言有相当的参考价值. AD:51CTO移动APP安全沙龙!马上要爆满,手慢没座位! 51CTO编辑注:本文是一篇论文,英文原文标题为The Google File System,在Google Labs上公布,由blademaster

java数据结构与算法之顺序表与链表深入分析

转载请注明出处(万分感谢!): http://blog.csdn.net/javazejian/article/details/52953190 出自[zejian的博客] 关联文章: java数据结构与算法之顺序表与链表设计与实现分析 java数据结构与算法之双链表设计与实现 ??数据结构与算法这门学科虽然在大学期间就已学习过了,但是到现在确实也忘了不少,因此最近又重新看了本书-<数据结构与算法分析>加上之前看的<java数据结构>也算是对数据结构的进一步深入学习了,于是也就打算

block的学习(block和timer的循环引用问题)

一.什么是回调函数? 回调函数,本质上也是个函数(搁置函数和方法的争议,就当这二者是一回事).由"声明"."实现"."调用"三部分组成. 在上面的例子中,我可以看出,函数amount(其实是Block),的声明和调用在A类中,而实现部分在B类中.也就是说,B类实现了amount函数,但并没有权限调用,最终还是 由A类触发调用.我们称这样的机制为"回调".意思是"虽然函数的实现写在B类中,但是真正的调用还是得由A类来完

聊聊并发(一)深入分析Volatile的实现原理

本文属于作者原创,原文发表于InfoQ:http://www.infoq.com/cn/articles/ftf-java-volatile 引言 在多线程并发编程中synchronized和Volatile都扮演着重要的角色,Volatile是轻量级的synchronized,它在多处理器开发中保证了共享变量的"可见性".可见性的意思是当一个线程修改一个共享变量时,另外一个线程能读到这个修改的值.它在某些情况下比synchronized的开销更小,本文将深入分析在硬件层面上Inter