Assembly Language for Beginners

(nextflipdebug2) #1

3.18. C++


element 3: 4
element 4: 5
element 5: 6
6
6619158


As it can be seen, there is no allocated buffer whenmain()starts. After the firstpush_back()call, a
buffer is allocated. And then, after eachpush_back()call, both array size and buffer size (capacity) are
increased. But the buffer address changes as well, becausepush_back()reallocates the buffer in the
heapeach time. It is costly operation, that’s why it is very important to predict the size of the array in the
future and reserve enough space for it with the.reserve()method.


Thelastnumberisgarbage: therearenoarrayelementsatthispoint, soarandomnumberisprinted. This
illustrates the fact thatoperator[]ofstd::vectordoes not check of the index is in the array’s bounds.
The slower.at()method, however, does this checking and throws anstd::out_of_rangeexception in
case of error.


Let’s see the code:


Listing 3.113: MSVC 2012 /GS- /Ob1

$SG52650 DB '%d', 0aH, 00H
$SG52651 DB '%d', 0aH, 00H


_this$ = -4 ; size = 4
Pos$ = 8 ; size = 4
?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z PROC ; std::vector<int,std::allocator
Ç>::at, COMDAT
; _this$ = ecx
push ebp
mov ebp, esp
push ecx
mov DWORD PTR _this$[ebp], ecx
mov eax, DWORD PTR _this$[ebp]
mov ecx, DWORD PTR _this$[ebp]
mov edx, DWORD PTR [eax+4]
sub edx, DWORD PTR [ecx]
sar edx, 2
cmp edx, DWORD PTR
Pos$[ebp]
ja SHORT $LN1@at
push OFFSET ??_C@_0BM@NMJKDPPO@invalid?5vector?$DMT?$DO?5subscript?$AA@
call DWORD PTR _imp?_Xout_of_range@std@@YAXPBD@Z
$LN1@at:
mov eax, DWORD PTR _this$[ebp]
mov ecx, DWORD PTR [eax]
mov edx, DWORD PTR __Pos$[ebp]
lea eax, DWORD PTR [ecx+edx*4]
$LN3@at:
mov esp, ebp
pop ebp
ret 4
?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z ENDP ; std::vector<int,std::allocator
Ç>::at


_c$ = -36 ; size = 12
$T1 = -24 ; size = 4
$T2 = -20 ; size = 4
$T3 = -16 ; size = 4
$T4 = -12 ; size = 4
$T5 = -8 ; size = 4
$T6 = -4 ; size = 4
_main PROC
push ebp
mov ebp, esp
sub esp, 36
mov DWORD PTR _c$[ebp], 0 ; Myfirst
mov DWORD PTR _c$[ebp+4], 0 ; Mylast
mov DWORD PTR _c$[ebp+8], 0 ; Myend
lea eax, DWORD PTR _c$[ebp]
push eax
call ?dump@@YAXPAUvector_of_ints@@@Z ; dump

Free download pdf