aihot  2020-11-12 09:25:31  OpenCV |   查看评论   
push eax 18 00A64B1A lea ecx,[var1] 19 00A64B1D push ecx 20 00A64B1E call Swap (0A61424h) 21 00A64B23 add esp,8

上面代码再次证明了,引用与指针的行为完全一致,只是编译器在编译时对引用作了更严格的限制。

四、引用占多大的内存空间

因为在在表达式中,使用引用实际上就像使用变量本身一样,所以直接用sizeof是得不到引用本身的大小的。

double var = 42.0;  double& ref = var;  cout << sizeof var << endl;  // print 8 
cout << sizeof ref << endl;   // print 8

我们可以通过定义一个只含有引用的类来解决这个问题:

1 class refClass{  2 private:  3     double& ref;  4 public:  5     refClass(double var = 42.0) :ref(var){}  6 }; 7 
8 cout << sizeof refClass << endl;  // print 4

所以结论就是引用和指针一样实际占内存空间4个字节。

 

除特别注明外,本站所有文章均为 赢咖4注册 原创,转载请注明出处来自C++的那些事:你真的了解引用吗

留言与评论(共有 0 条评论)
   
验证码:
[lianlun]1[/lianlun]