Classes are stored in exactly the same way as structures, except when they have virtual elements. In this case, there is an implicit vtable pointer as the first element (see below).
( ). , . (: http://en.cppreference.com/w/c/language/struct). C, ++ struct class ( public: private:).
struct class , , , "". ; - , double . 3 1 int . A struct - C , .
( static), (malloc new) ( : C/++ ). ( struct, . , .)
, . C ++ int : http://en.cppreference.com/w/c/language/object. , memcpy ( -POD- ++).
ABI , , , , - struct { char a; int b; }; (, x86-64 System V ABI, Linux , Windows, , int - 32- , 4- . ABI - , , C ++ " ", ABI , .)
, offsetof(struct_name, member), ( C11 ++ 11). . alignof ++ 11 _Alignof C11.
, , C . (, char, 4, . - , , 64 32- .)
ABI .. fooobar.com/tags/x86/.... Agner Fog ABI, .
( -)
class foo {
int m_a;
int m_b;
void inc_a(void){ m_a++; }
int inc_b(void);
};
int foo::inc_b(void) { return m_b++; }
( http://gcc.godbolt.org/):
foo::inc_b():
mov eax, DWORD PTR [rdi+4]
lea edx, [rax+1]
mov DWORD PTR [rdi+4], edx
ret
, this ( rdi, SysV AMD64 ABI). m_b 4 /. lea post-increment, eax.
inc_a, . , inline non-member. , .
++ C-, . ( ).
class foo {
public:
int m_a;
int m_b;
void inc_a(void){ m_a++; }
void inc_b(void);
virtual void inc_v(void);
};
void foo::inc_b(void) { m_b++; }
class bar: public foo {
virtual void inc_v(void);
};
void foo::inc_v(void) { m_b++; }
void bar::inc_v(void) { m_a++; }
; This time I made the functions return void, so the asm is simpler
; The in-memory layout of the class is now:
; vtable ptr (8B)
; m_a (4B)
; m_b (4B)
foo::inc_v():
add DWORD PTR [rdi+12], 1
ret
bar::inc_v():
add DWORD PTR [rdi+8], 1
ret
.globl foo::inc_b()
.set foo::inc_b(),foo::inc_v()
: add m32, imm8 , inc m32 Intel (- + ALU uops); , Pentium4 inc. gcc inc, - :/ INC ADD 1: ?
struct , , . , , struct , .
as-if : , asm, ( , , ++ "" ).
struct pair {
int m_a;
int m_b;
};
pair addsub(int a, int b) {
return {a+b, a-b};
}
int foo(int a, int b) {
pair ab = addsub(a,b);
return ab.m_a * ab.m_b;
}
( g++ 5.4) :
addsub(int, int):
lea edx, [rdi+rsi]
mov eax, edi
sub eax, esi
sal rax, 32
or rax, rdx
ret
foo(int, int):
lea eax, [rdi+rsi]
sub edi, esi
imul eax, edi
ret
, . X86-64 SysV ABI , . ABI .