Assembly Language for Beginners

(Jeff_L) #1
3.18. C++

“assign” method, the s1 and s2 strings are constructed. And with the help ofoperator+, the s3 string is
constructed.


Please note that there is no call to the c_str() method, because its code is tiny enough so the compiler
inlined it right there: if the string is shorter than 16 characters, a pointer to buffer is left inEAX, otherwise
the address of the string buffer located in theheapis fetched.

Next, we see calls to the 3 destructors, they are called if the string is longer than 16 characters: then the
buffers in theheaphave to be freed. Otherwise, since all three std::string objects are stored in the stack,
they are freed automatically, when the function ends.

As a consequence, processing short strings is faster, because of lessheapaccesses.

GCC code is even simpler (because the GCC way, as we saw above, is to not store shorter strings right in
the structure):

Listing 3.104: GCC 4.8.1
.LC0:
.string "Hello, "
.LC1:
.string "world!\n"
main:
push ebp
mov ebp, esp
push edi
push esi
push ebx
and esp, -16
sub esp, 32
lea ebx, [esp+28]
lea edi, [esp+20]
mov DWORD PTR [esp+8], ebx
lea esi, [esp+24]
mov DWORD PTR [esp+4], OFFSET FLAT:.LC0
mov DWORD PTR [esp], edi

call _ZNSsC1EPKcRKSaIcE

mov DWORD PTR [esp+8], ebx
mov DWORD PTR [esp+4], OFFSET FLAT:.LC1
mov DWORD PTR [esp], esi

call _ZNSsC1EPKcRKSaIcE

mov DWORD PTR [esp+4], edi
mov DWORD PTR [esp], ebx

call _ZNSsC1ERKSs

mov DWORD PTR [esp+4], esi
mov DWORD PTR [esp], ebx

call _ZNSs6appendERKSs

; inlined c_str():
mov eax, DWORD PTR [esp+28]
mov DWORD PTR [esp], eax

call puts

mov eax, DWORD PTR [esp+28]
lea ebx, [esp+19]
mov DWORD PTR [esp+4], ebx
sub eax, 12
mov DWORD PTR [esp], eax
call _ZNSs4_Rep10_M_disposeERKSaIcE
mov eax, DWORD PTR [esp+24]
mov DWORD PTR [esp+4], ebx
sub eax, 12
mov DWORD PTR [esp], eax
call _ZNSs4_Rep10_M_disposeERKSaIcE
Free download pdf