【C++&Java】构造函数的调用点


      程序员往往在new一个对象后,其构造函数就自动调用了。那么,有心的人会问: 类的构造函数到底是由谁在何时、何地调用的呢? 其实,在C++或者Java中,构造函数都是由编译器在生成一个对象后,自动在后面插入了一条调用构造函数的指令。详见下述代码。
一、Java实现
//Tree.java
public class Tree
{
     public Tree( int i)
     {
       System. out.println(i);
     }      
}

//Test.java
public class Test
{

       /**
       * @param args
       */
       public static void main(String[] args)
      {
            Tree tree = new Tree(1);

      }
}


//Test.class
// access flags 9
  public static main([Ljava/lang/String;)V
   L0 (0)
    LINENUMBER 11 L0
    NEW com/Tree    //执行 new一个Tree实例的操作
    DUP
    ICONST_1
    INVOKESPECIAL com/Tree.<init>(I)V      //编译器插入一条指令:调用Tree的构造函数,并有参数1传入
    ASTORE 1
   L1 (6)
    LINENUMBER 13 L1
    RETURN
   L2 (8)
    LOCALVARIABLE args [Ljava/lang/String; L0 L2 0
    LOCALVARIABLE tree Lcom/Tree; L1 L2 1
    MAXSTACK = 3
    MAXLOCALS = 2
}

 
二、C++实现
#include <iostream>
using namespace std;

class Xsd
{
int i;
public:
Xsd();
};

Xsd::Xsd()
{
cout<<"hello xsd"<<endl;
}


int main()
{
Xsd* a = new Xsd();

return 0;
}

//main.s
__ZN3XsdC2Ev:
LFB964:
pushl %ebp
LCFI0:
movl %esp, %ebp
LCFI1:
subl $24, %esp
LCFI2: //chentao:执行cout输出
movl $LC0, 4(%esp)
movl $__ZSt4cout, (%esp)
call __ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
movl $__ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_, 4(%esp)
movl %eax, (%esp)
call __ZNSolsEPFRSoS_E
leave
LCFI3:
ret
LFE964:
.globl __ZN3XsdC1Ev
.def __ZN3XsdC1Ev; .scl 2; .type 32; .endef
.set __ZN3XsdC1Ev,__ZN3XsdC2Ev
.def ___main; .scl 2; .type 32; .endef
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
LFB966:
pushl %ebp
LCFI4:
movl %esp, %ebp
LCFI5:
andl $-16, %esp
LCFI6:
pushl %esi
LCFI7:
pushl %ebx
LCFI8:
subl $40, %esp
LCFI9:
call ___main
movl $4, (%esp)
LEHB0:
call __Znwj //chentao: new Xsd()
LEHE0:
movl %eax, %ebx
movl %ebx, %eax
movl %eax, (%esp)
LEHB1:
call __ZN3XsdC1Ev //chentao:插入调用构造函数
LEHE1:
movl %ebx, 28(%esp)
movl $0, %eax
addl $40, %esp
popl %ebx
LCFI10:
popl %esi
LCFI11:
movl %ebp, %esp
LCFI12:
popl %ebp
LCFI13:
ret

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值