How operator new calls the constructor of class?

前端 未结 3 430
Happy的楠姐
Happy的楠姐 2021-01-13 09:45

I know that, new operator will call the constructor of class.

But how it\'s happening, what is ground level techniques used for this.

3条回答
  •  一整个雨季
    2021-01-13 10:00

    It's not really the new operator that calls the constructor. It is more the compiler that translate the following line:

    MyClass * mine = new MyClass();
    

    Into the following:

    MyClass * mine = malloc(sizeof(MyClass));  // Allocates memory
    mine->MyClass();                           // Calls constructor
    

    With other error handling code that other answers have noted.

提交回复
热议问题