From Schmid.wiki
Jump to: navigation, search

Memory Issues

A object without any attributes takes up 2 words (8 bytes) of memory. The memory requirements of an object is thus 2 words + memory requirement of attributes, e.g. an object of type Number:

class Number {             
public:                    
    Number(int x) : x(x) {}
    int x;                 
};                         

takes up 2 words + sizeof(int) = 3 words (12 bytes).

Example

This C++ code:

class Number {             
public:                    
    Number(int x) : x(x) {}
    int x;                 
};                         
int main(void) {           
    Number n(300);         
    return n.x;            
}

when compiled with:

g++ -S -mpreferred-stack-boundary=2 number.cpp

results in:

        ...
main:
        pushl   %ebp            # save caller stack pointer
        movl    %esp, %ebp      # copy stack pointer to base pointer
        subl    $12, %esp       # allocate space for n instance (3 words)

        movl    $300, 4(%esp)   # copy 300 to second argument
        leal    -4(%ebp), %eax  # copy address of n to eax
        movl    %eax, (%esp)    # copy n to first argument
        call    _ZN6NumberC1Ei  # call Number::Number(int) constructor
        movl    -4(%ebp), %eax  # return first value in n (n.x)
        leave
        ret

        ...
_ZN6NumberC1Ei:                 # Number::Number(int)
        pushl   %ebp            # save caller stack pointer
        movl    %esp, %ebp      # copy stack pointer to base pointer

        movl    8(%ebp), %edx   # copy first argument 'this' to %edx
        movl    12(%ebp), %eax  # copy second argument '300' to %eax
        movl    %eax, (%edx)    # copy '300' to this->x

        popl    %ebp            # restore caller stack frame
        ret                     # return to caller
        ...

Name Mangling

_ZN6NumberC1Ei

is decomposed as

_Z              mangled name prefix
  N             nested name (= a name that uses the scope operator)
   6Number      <length, id>
          C1    constructor
            E   end marker
             i  integer 

and thus:

Number::Number(int)