Onelong

分享知识,与你一起进步......
RSS icon Home icon
  • c++ 动态分配内存

    post by onelong / 2012-12-15 18:53 Saturday [C++]

     

    c++代码:

    class Person

    {

    private:

    char f;

    int num;

    public:

    Person()

    {

    num = 50;

    f = 'd';

    }

    };

     

    int main()

    {

    Person *p = new Person();

    return 0;

    }

    汇编代码如下:

     

    .arch armv4t

    .fpu softvfp

    .eabi_attribute 20, 1

    .eabi_attribute 21, 1

    .eabi_attribute 23, 3

    .eabi_attribute 24, 1

    .eabi_attribute 25, 1

    .eabi_attribute 26, 2

    .eabi_attribute 30, 6

    .eabi_attribute 18, 4

    .file "person.cpp"

    .section .text._ZN6PersonC1Ev,"axG",%progbits,_ZN6PersonC1Ev,comdat

    .align 2

    .weak _ZN6PersonC1Ev

    .type _ZN6PersonC1Ev, %function

    _ZN6PersonC1Ev://构造函数

    .fnstart

    .LFB2:

    @ Function supports interworking.

    @ args = 0, pretend = 0, frame = 8

    @ frame_needed = 1, uses_anonymous_args = 0

    @ link register save eliminated.

    str fp, [sp, #-4]!

    .LCFI0:

    add fp, sp, #0

    .LCFI1:

    sub sp, sp, #12

    .LCFI2:

    str r0, [fp, #-8] //分配内存的基地址,和上文提到罗嗦中有有点关联了

    ldr r3, [fp, #-8]

    mov r2, #50

    str r2, [r3, #4] //

    ldr r3, [fp, #-8]

    mov r2, #100

    strb r2, [r3, #0]

    ldr r3, [fp, #-8]

    mov r0, r3

    add sp, fp, #0

    ldmfd sp!, {fp}

    bx lr

    .LFE2:

    .cantunwind

    .fnend

    .size _ZN6PersonC1Ev, .-_ZN6PersonC1Ev

    .text

    .align 2

    .global main

    .type main, %function

    main:

    .fnstart

    .LFB4:

    @ Function supports interworking.

    @ args = 0, pretend = 0, frame = 8

    @ frame_needed = 1, uses_anonymous_args = 0

    stmfd sp!, {r4, fp, lr}

    .save {r4, fp, lr}

    .LCFI3:

    .setfp fp, sp, #8

    add fp, sp, #8

    .LCFI4:

    .pad #12

    sub sp, sp, #12

    .LCFI5:

    mov r0, #8 //分配内存的大小

    bl _Znwj //申请内存

    mov r3, r0

    mov r4, r3

    mov r3, r4

    mov r0, r3

    bl _ZN6PersonC1Ev //调用构造函数

    str r4, [fp, #-16]//对象指针存放,fp-8,fp-12被对象占用了

    mov r3, #0

    .L5:

    mov r0, r3

    sub sp, fp, #8

    ldmfd sp!, {r4, fp, lr}

    bx lr

    .LFE4:

    .fnend

    .size main, .-main

    .ident "GCC: (ctng-1.6.1) 4.4.3"

    .section .note.GNU-stack,"",%progbits

    通过对比可以知道,分配内存和调用构造函数是分开的。new int()是不会调用构造函数,或者他本身就没有构造函数。和java不同吧!new只是动态分配内存而已,和调用构造函数没有必然联系。我是这样认为的。
    或者说c++半残废的面向对象很容易给我们带来疑惑吧。c++之后语言里面,基本数据类型好像都不能new的吧!
    对于c++还是需要更多的对比汇编,才可以更透彻的理解吧!理解编译器,理解语法。。。

    标签: c c++ arm 汇编
    引用地址:
     

    我要评论