c++指针和引用异同

说白了c++中的引用就是指针。。至少底层实现是这样。。

一个例子说明。。一下

#include <stdio.h>

int main(int argc , char *argv[])
{
	int a = 9;
	int *b = &a;
	int &c = a;
	++c;
	*b += 2;
	return 0;
}


1:    #include <stdio.h>
2:
3:    int main(int argc , char *argv[])
4:    {
00401010   push        ebp
00401011   mov         ebp,esp
00401013   sub         esp,4Ch
00401016   push        ebx
00401017   push        esi
00401018   push        edi
00401019   lea         edi,[ebp-4Ch]
0040101C   mov         ecx,13h
00401021   mov         eax,0CCCCCCCCh
00401026   rep stos    dword ptr [edi]
5:        int a = 9;
00401028   mov         dword ptr [ebp-4],9
6:        int *b = &a;
0040102F   lea         eax,[ebp-4]
00401032   mov         dword ptr [ebp-8],eax
7:        int &c = a;
00401035   lea         ecx,[ebp-4]
00401038   mov         dword ptr [ebp-0Ch],ecx
8:        ++c;
0040103B   mov         edx,dword ptr [ebp-0Ch]
0040103E   mov         eax,dword ptr [edx]
00401040   add         eax,1
00401043   mov         ecx,dword ptr [ebp-0Ch]
00401046   mov         dword ptr [ecx],eax
9:        *b += 2;
00401048   mov         edx,dword ptr [ebp-8]
0040104B   mov         eax,dword ptr [edx]
0040104D   add         eax,2
00401050   mov         ecx,dword ptr [ebp-8]
00401053   mov         dword ptr [ecx],eax
10:       return 0;
00401055   xor         eax,eax
11:   }
00401057   pop         edi
00401058   pop         esi
00401059   pop         ebx
0040105A   mov         esp,ebp
0040105C   pop         ebp
0040105D   ret

begin
 EAX = 00781798 EBX = 7EFDE000
 ECX = 00000001 EDX = 00781810
 ESI = 00000000 EDI = 00000000
 EIP = 00401010 ESP = 0018FF4C
 EBP = 0018FF88 EFL = 00000212

0018FF25  02 00 00 00 08 00 00  .......
0018FF2C  02 00 00 00 44 2E 42  ....D.B
0018FF33  00 83 00 00 00 03 00  .......
0018FF3A  00 00 44 FF 18 00 A8  ..D....
0018FF41  13 40 00 54 FF 18 00  .@.T...
0018FF48  23 12 40 00 49 11 40  #.@.I.@

end
0018FF25  CC CC CC CC CC CC CC  烫烫烫.
0018FF2C  CC CC CC CC CC CC CC  烫烫烫.
0018FF33  CC CC CC CC CC CC CC  烫烫烫.
0018FF3A  CC CC 44 FF 18 00 44  烫D...D
0018FF41  FF 18 00 0C 00 00 00  .......  12    由9---->12
0018FF48  88 FF 18 00 49 11 40  ....I.@
0018FF4F  00 01 00 00 00 98 17  .......
8:        ++c;      引用操作
0040103B   mov         edx,dword ptr [ebp-0Ch]
0040103E   mov         eax,dword ptr [edx]
00401040   add         eax,1
00401043   mov         ecx,dword ptr [ebp-0Ch]
00401046   mov         dword ptr [ecx],eax
9:        *b += 2;  指针操作
00401048   mov         edx,dword ptr [ebp-8]
0040104B   mov         eax,dword ptr [edx]
0040104D   add         eax,2
00401050   mov         ecx,dword ptr [ebp-8]
00401053   mov         dword ptr [ecx],eax

不多说,操作方式基本一样(vc6 debug版本)


引用是不是指针一目了然。。

cpp
您的回应...

相关话题

查看全部

也许你感兴趣

换一批

热门标签

更多