Assembly Language for Beginners

(Jeff_L) #1

3.18. C++


mov eax, DWORD PTR [esp+20]
mov DWORD PTR [esp+4], ebx
sub eax, 12
mov DWORD PTR [esp], eax
call _ZNSs4_Rep10_M_disposeERKSaIcE
lea esp, [ebp-12]
xor eax, eax
pop ebx
pop esi
pop edi
pop ebp
ret

It can be seen that it’s not a pointer to the object that is passed to destructors, but rather an address 12
bytes (or 3 words) before, i.e., a pointer to the real start of the structure.


std::string as a global variable


Experienced C++ programmers knows that global variables ofSTL^30 types can be defined without prob-
lems.


Yes, indeed:


#include <stdio.h>
#include


std::string s="a string";


int main()
{
printf ("%s\n", s.c_str());
};


But how and wherestd::stringconstructor will be called?


In fact, this variable is to be initialized even beforemain()start.


Listing3.105: MSVC 2012: hereis howa global variable is constructed and alsoits destructor is registered


??Es@@YAXXZ PROC
push 8
push OFFSET $SG39512 ; 'a string'
mov ecx, OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s
call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ;⤦
Ç std::basic_string<char,std::char_traits,std::allocator >::assign
push OFFSET ??
Fs@@YAXXZ ; `dynamic atexit destructor for 's''
call _atexit
pop ecx
ret 0
??__Es@@YAXXZ ENDP


Listing 3.106: MSVC 2012: here a global variable is used inmain()

$SG39512 DB 'a string', 00H
$SG39519 DB '%s', 0aH, 00H


_main PROC
cmp DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 16
mov eax, OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s
cmovae eax, DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A
push eax
push OFFSET $SG39519 ; '%s'
call _printf
add esp, 8
xor eax, eax
ret 0
_main ENDP


(^30) (C++) Standard Template Library

Free download pdf