前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >深入分析C++引用

深入分析C++引用

作者头像
全栈程序员站长
发布2022-07-13 18:22:08
1690
发布2022-07-13 18:22:08
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

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

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

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

引言

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

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

背景

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

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

2. 通过地址 訪问 / 传递变量 – 这样的方法就是指针

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

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

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

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

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

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

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

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

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

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

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

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

代码语言:javascript
复制
#include <iostream.h><br />class Test<br />{<br />    int &i;   // int *const i;<br />    int &j;   // int *const j;<br />    int &k;   // int *const k;<br />};<br />int main()<br />{<br />    // This will print 12 i.e. size of 3 pointers<br />    cout<<  “size of class Test = ”  <<   sizeof(class Test)  <<endl;<br />    return 0;<br />} 

结论

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

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

代码语言:javascript
复制
#include <iostream.h><br />class A<br />{<br />public:<br />         virtual void print() { cout<<“A..”<<endl; }<br />};<br />class B : public A<br />{<br />public:<br />         virtual void print() { cout<<“B..”<<endl; }<br />};</p> <p>class C : public B<br />{<br />public:<br />         virtual void print() { cout<<“C..”<<endl; }<br />};<br />int main()<br />{<br />         C c1;<br />         A &a1 = c1;<br />         a1.print(); // prints C<br />         A a2 = c1;<br />         a2.print(); // prints A<br />         return 0;<br />} 

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

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/118142.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年12月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档